Problem
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
ExampleGiven nums = [-2,0,1,3], target = 2, return 2.
Explanation:Because there are two triplets which sums are less than 2:
[-2, 0, 1]
[-2, 0, 3]
Could you solve it in O(n2) runtime?
Solutionpublic class Solution { /** * @param nums: an array of n integers * @param target: a target * @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k] < target */ public int threeSumSmaller(int[] nums, int target) { // Write your code here if (nums.length < 3) return 0; Arrays.sort(nums); if (nums[0] >= target) return 0; int count = 0; for (int i = 0; i < nums.length-2; i++) { int start = i+1, end = nums.length-1; int sum = target - nums[i]; while (start < end) { if (nums[start] + nums[end] < sum) { count += end-start; start++; } else { end--; } } } return count; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/69649.html
摘要:排序法复杂度时间空间思路解题思路和一样,也是先对整个数组排序,然后一个外层循环确定第一个数,然后里面使用头尾指针和进行夹逼,得到三个数的和。 3Sum Smaller Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 = target){ ...
摘要:题目链接,从小到大排序固定第一个数字,从后面的数字里选第二个第三个后两个数字,用来找,从开始因为所有之间的数和组合都 3Sum Smaller 题目链接:https://leetcode.com/problems... sort,从小到大排序 固定第一个数字index = i,从后面的数字里选第二个第三个 后两个数字,用2 points来找,从j = i + 1, k = len(...
摘要:这个题和的做法基本一样,只要在循环内计算和最接近的和,并赋值更新返回值即可。 Problem Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three intege...
摘要:双指针法的解法。然后用和夹逼找到使三数和为零的三数数列,放入结果数组。对于这三个数,如果循环的下一个数值和当前数值相等,就跳过以避免中有相同的解。 Problem Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplet...
摘要:由于这道题目不是查找而是选择第一个的数的位置,所以语句里面可以把和归为同一个分支,因为存在包含重复数的情况,所以要和一样,指针前移替换。那么另一个分支,除了将后移,还要更新返回值。约束条件为的两种写法 Problem Give you an integer array (index from 0 to n-1, where n is the size of this array, va...
阅读 1236·2021-11-16 11:44
阅读 3707·2021-10-09 10:01
阅读 1689·2021-09-24 10:31
阅读 3668·2021-09-04 16:41
阅读 2471·2021-08-09 13:45
阅读 1167·2019-08-30 14:08
阅读 1744·2019-08-29 18:32
阅读 1614·2019-08-26 12:12