【LeetCode】15. 3Sum 三个数和为0
题目:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路:先对数组排序,for循环选定每个位置的数,在下个位置及末尾设置两个索引,从两边往中间走,找出两个数满足三者的和为0。因为数组有序,所以当和大于0时,右边索引左移,反之,左边索引右移。
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
int len=nums.length;
if(len<3) return result;
int sum=0;
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
if(nums[i]>0) break;
if(i>0&&nums[i]==nums[i-1]) continue;
int begin=i+1,end=len-1;
while(begin<end){
sum=nums[i]+nums[begin]+nums[end];
if(sum==0){
List<Integer> tem=new ArrayList<Integer>();
tem.add(nums[i]);
tem.add(nums[begin]);
tem.add(nums[end]);
result.add(tem);
begin++;end--;
while(begin<end&&nums[begin]==nums[begin-1]) begin++;
while(begin<end&&nums[end]==nums[end+1]) end--;
}else if(sum<0){
begin++;
}else end--;
}
}
return result;
}
}
浙公网安备 33010602011771号