-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathThreeSum.java
More file actions
96 lines (71 loc) · 2.52 KB
/
Copy pathThreeSum.java
File metadata and controls
96 lines (71 loc) · 2.52 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Problem: https://leetcode.com/problems/3sum/
* Tidbit: https://stackoverflow.com/questions/6810691/instantiating-a-list-in-java
*/
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Arrays;
public class ThreeSum {
/* O(n3) */
public static List<List<Integer>> threeSumAlgo1(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0 ){
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
result.add(temp);
}
}
}
}
return result;
}
/* O(n2) using two pointers*/
public static List<List<Integer>> threeSumAlgo2(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
HashSet<Integer> track = new HashSet<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
//fix the value
int a = nums[i];
int start = i + 1;
int end = nums.length - 1;
if (i > 0 && (nums[i] == nums[i - 1])) {
continue;
}
while (start < end ) {
int b = nums[start];
int c = nums[end];
int sum = a + b + c;
if (start > i + 1 && (nums[start] == nums[start - 1])) {
start = start + 1;
continue;
}
if (sum == 0) {
List<Integer> tempResult = new ArrayList<>();
tempResult.add(a);
tempResult.add(b);
tempResult.add(c);
result.add(tempResult);
start = start + 1;
end = end - 1;
} else if (sum > 0 ) {
end = end - 1;
} else {
start = start + 1;
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {-1,0,1,2,-1,-4};
System.out.println("\n**Algo1\n" + threeSumAlgo1(nums));
System.out.println("\n**Algo2\n" + threeSumAlgo2(nums));
}
}