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

題意:求三個(gè)數(shù)字合為0,并且集合不重復(fù)的結(jié)果集合。

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;  
    }  
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容