15. 3Sum(Leetcode每日一題-2020.06.12)

Problem

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.

Example

Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

Solution

雙指針,注意去重

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        
        vector<vector<int>> ret;
        
        if(num.size() < 3)
            return ret;
            
        
        sort(num.begin(),num.end());
        
        
        
       
        
        for(int i = 0;i<num.size();i++)
        {
            //去重
            if( i != 0 && num[i] == num[i -1])
                continue;
                
            int j = i + 1;
            int k = num.size() - 1;
            
            while(j < k)
            {
                int sum = num[i] + num[j] + num[k];
               
                    if(sum == 0)
                    {
                        vector<int> tmp;
                        tmp.push_back(num[i]);
                        tmp.push_back(num[j]);
                        tmp.push_back(num[k]);
                        sort(tmp.begin(),tmp.end());
                        ret.push_back(tmp);
                        //尋找其他可能的2個數,順帶去重  
                        while (++j < k  && num[j-1] == num[j])  
                        {  
                            //do nothing  
                        }  
                        while (--k > j && num[k+1] == num[k])  
                        {  
                            //do noghing  
                        }  
                    }
                    if(sum > 0)
                        k--;
                    if(sum < 0)
                        j++;
            }
                
        }
        
        return ret;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章