题目描述:
Given an array of n integers nums and an integer 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.
Follow up: Could you solve it in O(n2) runtime?
Example 1:
Input: nums = [-2,0,1,3], target = 2
Output: 2
Explanation: Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]
Example 2:
Input: nums = [], target = 0
Output: 0
Example 3:
Input: nums = [0], target = 0
Output: 0
Constraints:
n == nums.length
0 <= n <= 300
-100 <= nums[i] <= 100
-100 <= target <= 100
Time complexity:
O
O
O(
N
2
N^{2}
N2)
Space complexity:
O
O
O(
1
1
1)
双指针:
根据解决此类较简单的问题twoSum版本,现排序,然后我们可以用通向双指针找到满足两数之和小于target的index即 nums[i]+nums[j]<target。左指针从左往右递增,右指针从右往左递减。注意在此题中,要求我们找到所有满足的组合后数。所以以 [1, 2, 3, 5, 8], target=7. 为例子,当左指针 left 指向1,右指针 right 指向5满足 1 + 5 < 7 后我们发现因为数组是排过序的则[1, 2], [1, 3]也都满足条件,所以 总的组合数 sum += right - left;
class Solution {
public int threeSumSmaller(int[] nums, int target) {
Arrays.sort(nums);
int sum = 0;
for(int i = 0; i < nums.length-2; i++){
sum += twoSumSmaller(nums, i+1, target - nums[i]);
}
return sum;
}
private int twoSumSmaller(int[] nums, int start, int target){
int sum = 0;
int left = start;
int right = nums.length - 1;
while(left < right){
if(nums[left] + nums[right] < target){
sum += right - left;
left++;
}else{
right--;
}
}
return sum;
}
}