题目描述
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]
]
解题思路
对比2Sum,可以将3Sum分解为遍历a加上b+c=-a来考虑。
先对数组进行排序,然后用两指针向中心逼近来求2Sum。
此题可借以练习排序。
源码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int length=nums.length;
int i=0;
int lo=0,hi=0,sum=0;
List<List<Integer>> res=new ArrayList<>();
for(;i<length-2;i++){
if(i==0||(nums[i]!=nums[i-1])){
lo=i+1;
hi=length-1;
sum=0-nums[i];
while(lo<hi){
if(nums[lo]+nums[hi]==sum){
res.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]<sum){
lo++;
}else{
hi--;
}
}
}
}
return res;
}
private void sort(int[]nums){
//可自己选择实现排序
}
}
近期评论