Use stl to avoid dumplicates C++ 72ms


  • 0
    W
    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            int len = nums.size();
            vector<vector<int> >    res;
            if(len < 4) return res;
            sort(nums.begin(),nums.end());
            for(int first = 0;first <= len - 1;++first){
                int target_3 = target - nums[first];
                for(int second = first + 1;second <= len - 1;++second){
                    int target_2 = target_3 - nums[second];
                    int mid = second + 1;
                    int last = len - 1;
                    while(mid < last){
                        int sum_2 = nums[mid] + nums[last];
                        if(sum_2 < target_2){
                            ++mid;
                        }
                        else if(sum_2 > target_2){
                            --last;
                        }
                        else{
                            vector<int> vi;
                            vi.push_back(nums[first]);
                            vi.push_back(nums[second]);
                            vi.push_back(nums[mid]);
                            vi.push_back(nums[last]);
                            res.push_back(vi);
                            ++ mid;
                            -- last;
                        }
                    }
                }
            }
            sort(res.begin(),res.end());
            res.erase(unique(res.begin(),res.end()),res.end());
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.