/**
* 3sum变形题,同样也固定一个数字,双指针移动确定其后的另外两个数
* 该题下标不同就算不同数字,所以不用去重
*/
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
int length = nums.length, ans = 0;
if (length < 3)
return ans;
Arrays.sort(nums);
for (int i = 0; i < length - 2; i++) {
if (nums[i] * 3 >= target)
return ans;
int start = i + 1, end = length - 1;
while (start < end) {
if (nums[i] + nums[start] + nums[end] < target) {
ans += end - start; // start与end及其之前的所有数字都能成功匹配,算上后start后移一位
start++; // 此后不能用while处理后面相同的数字,因为前一位的三个数中间可能有后面相同的数,对于后面的数就不是同样的情况了
} else {
end--;
while (start < end && nums[end] == nums[end + 1]) // 此处不是为了去重,而是优化,因为相同的所有数字都不会符合要求所以直接跳过
end--;
}
}
}
return ans;
}
}