3Sum
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]
]
时间 o(n^2), space o(n)
不要忘记 先排序,然后循环的时候去重
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length == 0){
return res;
}
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
//去重
if(i > 0 && nums[i] == nums[i-1]) continue;
int low = i+1, hight = nums.length -1, sum = 0-nums[i];
while(low < hight){
if(nums[low] + nums[hight] == sum){
List<Integer> list = new ArrayList<>();
list.add(nums[low]);
list.add(nums[hight]);
list.add(nums[i]);
res.add(list);
//res.add(Array.asList())
//退出循环时,low在最后一个重复的数组,hight也是一样,所以最后要
while(low < hight && nums[low] == nums[low+1] ) low++;
while(low < hight && nums[hight] == nums[hight-1]) hight--;
low++;
hight--;
}
else if(nums[low] + nums[hight] < sum){
low++;
}else{
hight--;
}
}
}
return res;
}
}
Last updated