-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTripletsWithSumK.java
More file actions
46 lines (39 loc) · 1.13 KB
/
TripletsWithSumK.java
File metadata and controls
46 lines (39 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TripletsWithSumK {
public static void main(String[] args) {
int[] nums = { 5, 2, 7, 6, 1, 8 };
int[][] tripletsWithSumK = new TripletsWithSumK().getTripletsWithSumK(nums, 15);
for (int i = 0; i < tripletsWithSumK.length; i++) {
for (int j = 0; j < tripletsWithSumK[i].length; j++) {
System.out.print(tripletsWithSumK[i][j] + ", ");
}
System.out.println();
}
}
public int[][] getTripletsWithSumK(int[] nums, int k) {
if (nums == null || nums.length < 3) {
return new int[0][0];
}
List<int[]> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int start = i + 1;
int end = (i == nums.length - 1) ? nums.length - 2 : nums.length - 1;
while (start < end) {
if (nums[start] + nums[end] == k - nums[i]) {
int[] curResult = { nums[i], nums[start], nums[end] };
result.add(curResult);
start++;
end--;
} else if (nums[start] + nums[end] < k - nums[i]) {
start++;
} else {
end--;
}
}
}
return result.toArray(new int[result.size()][3]);
}
}