三数之和15

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
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;


//三数之和15
public class Threesum15 {
public static void main(String[] args) {
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> list = new Solution().threeSum(nums);
for(List<Integer> itemList : list){
System.out.println();
for (Integer item : itemList) {
System.out.print(item + "\t");
}
}
}
}
class Solution {
public List<List<Integer>> threeSum(int[] nums) {

List<List<Integer>> res = new ArrayList<>();

if (nums.length < 3) {
return res;
}
//排序
Arrays.sort(nums);


for(int i = 0; i < nums.length; i++){
//如果第一个就 > 0,那绝对凑不出来 三个 = 0
if (nums[i] > 0) {
return res;
}

//对a去重
if (i > 0 &&nums[i] == nums[i - 1]) {
continue;
}

int left = i + 1;
int right = nums.length - 1;

while(right > left){
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
left++;
}else if (sum > 0) {
right--;
}else if (sum == 0){
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
//后面两位去重
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}

}

return res;
}
}

add

  1. 多复习几遍。这个题目确实棘手,尤其是去重处理。我能写出来,但是不知道为什么在哪里去重。
  2. 回滚JavaSE。关于JavaSE中间关于集合那段的语法有点忘了。只记得JavaSE最基础的if,when,while,for了。
  3. 我不知道引入什么包,这点有点寄。