这题是允许重复的数字的,因为只要保证下标满足i, j, k
with 0 <= i < j < k < n
就好。
所以不需要开始的去重!
再有,这种求小于某值或是大于某值的,看好了,求数量是坐标的相减
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
if (nums == null || nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int count = 0;
for (int i = 0; i < nums.length - 2; i++) {
// if (i > 0 && nums[i] == nums[i - 1]) {
// continue;
// }
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum >= target) {
right--;
} else {
count = count + right - left;
left++;
}
// if (sum < target) {
// count++;
// right--;
// while (left < right && nums[right] == nums[right + 1]) {
// right--;
// }
// } else if (sum > target) {
// right--;
// } else {
// right--;
// left++;
// }
}
}
return count;
}
}