美文网首页ACM题库~
LeetCode 15. 3Sum

LeetCode 15. 3Sum

作者: 关玮琳linSir | 来源:发表于2017-09-11 10:06 被阅读7次

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: 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]
]

题意:求三个数字合为0,并且集合不重复的结果集合。

java:

class Solution {
   
    public List<List<Integer>> threeSum(int[] nums) {  
        List<List<Integer>> res = new ArrayList<List<Integer>>();  
        int len=nums.length;  
        if(len<3)return res;  
        Arrays.sort(nums);  
        for(int i=0;i<len;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){  
                int sum=nums[i]+nums[begin]+nums[end];  
                if(sum==0){  
                    List<Integer> list = new ArrayList<Integer>();  
                    list.add(nums[i]);list.add(nums[begin]);list.add(nums[end]);  
                    res.add(list);  
                    begin++;end--;  
                    while(begin<end && nums[begin]==nums[begin-1])begin++;  
                    while(begin<end && nums[end]==nums[end+1])end--;  
                }else if(sum>0)end--;  
                else begin++;  
            }  
        }  
        return res;  
    }  
}

相关文章

网友评论

    本文标题:LeetCode 15. 3Sum

    本文链接:https://www.haomeiwen.com/subject/cmpxsxtx.html