其他分享
首页 > 其他分享> > 剑指 Offer II 007. 数组中和为 0 的三个数

剑指 Offer II 007. 数组中和为 0 的三个数

作者:互联网

暴力去重

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {


        map<int, int> cnt;
        int n = nums.size();
        for(int i = 0; i < n; i++)
        {
            if(cnt[nums[i]] == 0)
                cnt[nums[i]] = 1;
            else
                cnt[nums[i]]++;
        }
        vector<vector<int> > ret;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < n; i++)
        {
            if(i > 0 && nums[i] == nums[i - 1]) continue;
            for(int j = i + 1; j < n; j++)
            {
                // cout << nums[j] << " " << nums[j - 1] << endl;
                if((j > i + 1) && (nums[j] == nums[j - 1]))
                {

                    continue;
                }
                vector<int> temp;
                
                int kk = 0 - (nums[i] + nums[j]);

                if(kk < nums[j]) continue;
                if((kk == nums[j] && cnt[kk] > 1) || kk != nums[j] && cnt[kk])
                {

                    if(kk == nums[i])
                    {
                        if(i > 1 && kk == nums[i - 1]) continue;
                        if(cnt[kk] >= 3)
                        {
                            temp.push_back(nums[i]);
                            temp.push_back(nums[j]);
                            temp.push_back(kk);
                        }
                        
                    }
                    else{
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(kk);
                    }
                    // cout << nums[i] << " " << nums[j] << " " << kk << " " << r << endl;
                }
                if(temp.size() == 3)
                {
                    sort(temp.begin(), temp.end());
                    ret.push_back(temp);
                }
            }
        }

        // sort(ret.begin(), ret.end());
        // int k = unique(ret.begin(), ret.end()) - ret.begin();
        // cout << k << " " << ret.size() << endl;
        vector<vector<int> > R;
        for(int i = 0; i < ret.size(); i++)
        {
            R.push_back(ret[i]);


        }


    return R;


    }
};

 

标签:cnt,temp,nums,kk,Offer,back,II,007,push
来源: https://www.cnblogs.com/WTSRUVF/p/16074614.html