Description
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]
Thinking process
- Just a variant of the 3Sum closest problem
- Sort the array, pick an item, run the TwoSum subroutine on the rest of the array behind it
public int threeSumSmaller(int[] nums, int target) {
Arrays.sort(nums);
int count = 0;
for(int i=0; i<nums.length; i++){
int low = i + 1;
int high = nums.length - 1;
while(low < high){
if(nums[i] + nums[low] + nums[high] < target){
count += (high - low);
low++;
}else{
high--;
}
}
}
return count;
}
Complexity
O(n2)