Skip to content

Commit 81603c3

Browse files
authored
Create 15. 3Sum
1 parent 433183f commit 81603c3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

15. 3Sum

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class Solution {
2+
public List<List<Integer>> threeSum(int[] nums) {
3+
List<List<Integer>> results = new ArrayList<>();
4+
if( nums == null || nums.length <= 2){
5+
return results;
6+
}
7+
Arrays.sort(nums);
8+
for(int i = 0; i < nums.length - 2; i++){
9+
if(i!= 0 && nums[i] == nums[i - 1]){
10+
continue;
11+
}
12+
int left = i+1;
13+
int right = nums.length - 1;
14+
while(left < right){
15+
if(nums[i] + nums[left] + nums[right] > 0){
16+
right --;
17+
18+
}else if(nums[i] + nums[left] + nums[right] == 0){
19+
ArrayList <Integer> list = new ArrayList<>();
20+
list.add(nums[i]);
21+
list.add(nums[left]);
22+
list.add(nums[right]);
23+
results.add(list);
24+
left ++;
25+
right --;
26+
while(left < right && nums[left] == nums[left - 1]){// 关键点!!!
27+
left ++;
28+
}
29+
while(right > left && nums[right] == nums[right + 1]){
30+
right --;
31+
}
32+
}else{
33+
left ++;
34+
35+
}
36+
}
37+
}
38+
return results;
39+
}
40+
}

0 commit comments

Comments
 (0)