Given an array of N=10^6 int32 and an int32 X, compute the exact number of triples (a, b, c) of distinct elements of the array so that a + b + c <= X
public int threeSumSmaller(int[] nums, int target) {
if (nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int res = 0;
for (int i = 0; i < nums.length - 2; ++i) {
if (nums[i] + nums[i + 1] + nums[i + 2] >= target) {
break;
}
int curr = nums[i];
int lo = i + 1, hi = nums.length - 1;
while (lo < hi) {
while (lo < hi && curr + nums[lo] + nums[hi] >= target) {
--hi;
}
res += hi - lo;
++lo;
}
}
return res;
}