Question
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
.
For example, given nums = [-2, 0, 1, 3]
, and target = 2.
Return 2. Because there are two triplets which sums are less than 2:
[-2, 0, 1] [-2, 0, 3]
Solution
由于这道题题目并不要求去重,所以我们就不考虑重复。
题目虽然提到了index,但我们发现返回的是个数。因此还是可以先将数组排序,用2Sum的方法。
注意到对于nums[l] + nums[r]
如果已经小于target,那么nums[l] + nums[r - 1], nums[l] + nums[r - 2], nums[l] + nums[r - 3], ...一定也满足条件。所以count += r - l。之后l++,看后一个左指针指向的数。
Time complexity O(n2)
1 public class Solution { 2 public int threeSumSmaller(int[] nums, int target) { 3 Arrays.sort(nums); 4 int count = 0; 5 for (int i = 0; i < nums.length; i++) { 6 int tmpTarget = target - nums[i]; 7 int start = i + 1, end = nums.length - 1; 8 while (start < end) { 9 int sum = nums[start] + nums[end]; 10 if (sum >= tmpTarget) { 11 end--; 12 } else { 13 count += end - start; 14 start++; 15 } 16 } 17 } 18 return count; 19 } 20 }
时间: 2024-10-08 15:46:30