-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy paththreeSum.java
More file actions
47 lines (47 loc) · 1.52 KB
/
threeSum.java
File metadata and controls
47 lines (47 loc) · 1.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
import java.util.*;
public class threeSum {
public static void main(String[] args){
int[] nums = new int[] {-2,0,1,1,2};
threeSum obj = new threeSum();
System.out.println(obj.threeSum(nums));
}
/* Approach: for loop + two sum
Time: O(n^2)
Space: O(1)
* */
private List<List<Integer>> threeSum(int[] nums){
List<List<Integer>> result = new ArrayList();
if(nums == null || nums.length < 3){
return result;
}
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
// 关键要想清楚,2SUM面对duplicate怎么办,3SUM面对duplicate怎么办
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
// two sum
int lo = i + 1, hi = nums.length - 1;
while(lo < hi){
//consider duplicates
//2 sum应对duplica
if(nums[lo] + nums[hi] == 0 - nums[i]){
result.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
while(lo < hi && nums[lo] == nums[lo+1]){
lo ++;
}
while(lo < hi && nums[hi] == nums[hi-1]){
hi --;
}
lo ++;
hi --;
}else if(nums[lo] + nums[hi] < 0 - nums[i]){
lo ++;
}else{
hi --;
}
}
}
return result;
}
}