ThreeSum

Problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

Solution

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
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i = 0; i < nums.length - 2; i++){
// 跳过重复元素
if(i > 0 && nums[i] == nums[i-1]) continue;
// 计算2Sum
ArrayList<List<Integer>> curr = twoSum(nums, i, 0 - nums[i]);
res.addAll(curr);
}
return res;
}

private ArrayList<List<Integer>> twoSum(int[] nums, int i, int target){
int left = i + 1, right = nums.length - 1;
ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
while(left < right){
if(nums[left] + nums[right] == target){
ArrayList<Integer> curr = new ArrayList<Integer>();
curr.add(nums[i]);
curr.add(nums[left]);
curr.add(nums[right]);
res.add(curr);
do {
left++;
}while(left < nums.length && nums[left] == nums[left-1]);
do {
right--;
} while(right >= 0 && nums[right] == nums[right+1]);
} else if (nums[left] + nums[right] > target){
right--;
} else {
left++;
}
}
return res;
}
}

Key

tips:很久没有写Java了,花了点时间去整理了一些知识,所以上面的算法其实是ctrl+v的,现在整理一下list相关的知识:

1.List<List>为嵌套的list集合,声明方式

List<List****> list = new Array***()*

or

List<List> list = new ArrayList<>();//recomend

2.List是一个接口,而ArrayList是List接口的一个实现类

List list = new List();//是错误的用法

List list = new ArrayList();//list会丢失ArrayList的trimToSize()方法

ArrayList list=newArrayList()

3.然后明天再回来重新写这道题