Another way to eliminate duplicates


  • 0
    G
    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            vector<vector<int>> ret;
            if(nums.size() < 3) return ret;
            sort(nums.begin(), nums.end());
            for(int i = 0; i < nums.size() - 2; i++){
                if(i > 0 && nums[i] == nums[i-1]) continue;
                int l = i + 1;
                int r = nums.size() - 1;
                while(l < r){
                    int sum = nums[l] + nums[r] + nums[i];
                    if(sum == 0){
                        ret.push_back({nums[i], nums[l], nums[r]});
                    }
                    if(sum <= 0){
                        do{
                            l++;
                        }while(l < r && nums[l] == nums[l-1]);
                    }
                    if(sum >= 0){
                        do{
                            r--;
                        }while(l < r && nums[r] == nums[r+1]);
                    }
                }
            }
            return ret;
        }
    };

Log in to reply
 

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