LeetCode 15. 3Sum

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

你可能感兴趣的:(LeetCode 15. 3Sum)