-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreeSum.java
68 lines (51 loc) · 1.51 KB
/
ThreeSum.java
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.leetcode.algorithms.medium.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import com.leetcode.util.InputUtil;
public class ThreeSum {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String[] inputs = InputUtil.inputArr(scanner.next());
int[] nums = InputUtil.integerArr(inputs);
// Print output
List<List<Integer>> result = threeSum(nums);
for (List<Integer> list : result) {
System.out.println(Arrays.toString(list.toArray(new Integer[list.size()])));
}
scanner.close();
}
static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> listOfList = new ArrayList<>();
if (nums.length < 3) {
return listOfList;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int firstPointer = i + 1;
int secondPointer = nums.length - 1;
while (firstPointer < secondPointer) {
int sum = nums[i] + nums[firstPointer] + nums[secondPointer];
if (sum == 0) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[firstPointer]);
list.add(nums[secondPointer]);
Collections.sort(list);
if (!listOfList.contains(list)) {
listOfList.add(list);
}
++firstPointer;
} else if (sum > 0) {
--secondPointer;
} else {
++firstPointer;
}
}
}
return new ArrayList<List<Integer>>(listOfList);
}
}