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.
publicclassSolution {
publicintthreeSumSmaller(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
int count = 0;
for (int i = 0; i < n - 2; i++) {
int j = i + 1, k = n - 1;
while (j < k) {
if (nums[i]+ nums[j]+ nums[k]< target) {
count += k - j;
j++;
} else {
k--;
}
}
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defthreeSumSmaller(self, nums, target):
nums.sort()
n = len(nums)
count =0for i in range(n -2):
j, k = i +1, n -1while j < k:
if nums[i] + nums[j] + nums[k] < target:
count += k - j
j +=1else:
k -=1return count