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, 1]
[-2, 0, 3]
思路:将数组排序。枚举第一个数,假设它为第i个数,则triplet中的第二个数和第三个数则在数组[i+1, n-1]中。我们用两个指针left和right来找这两个数,向中间搜索。
当nums[i] + nums[left] + nums[right] < target时,right指针向左移动仍然会符合,因此这时候满足条件的结果数有right - left个,记下这个数值,然后将left向右移动一位;否则将right向左移动一位。最后返回所有的结果数之和。时间复杂度为O(N^2)。
1 class Solution { 2 public: 3 int threeSumSmaller(vector<int>& nums, int target) { 4 int count = 0, len = nums.size(); 5 sort(nums.begin(), nums.end(), less<int>()); 6 for (int i = 0; i < len - 2; i++) { 7 int left = i + 1, right = len - 1; 8 while (left < right) { 9 if (nums[i] + nums[left] + nums[right] < target) { 10 count += right - left; 11 left++; 12 } else { 13 right--; 14 } 15 } 16 } 17 return count; 18 } 19 };