3Sum Smaller
Input:
nums
=
[-2,0,1,3]
, and
target
= 2
Output:
2
Explanation:
Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]Solution & Analysis
Last updated
Input:
nums
=
[-2,0,1,3]
, and
target
= 2
Output:
2
Explanation:
Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]Last updated
class Solution {
public int threeSumSmaller(int[] nums, int target) {
Arrays.sort(nums);
int count = 0;
for (int i = 0; i < nums.length - 2; i++) {
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
if (nums[i] + nums[j] + nums[k] >= target) {
k--;
} else {
count += k - j;
j++;
}
}
}
return count;
}
}