a feasible solution


  • 0
    E
    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            vector<vector<int>> results;
            sort(nums.begin(), nums.end());
            
            for (size_t i = 0; i < nums.size(); ++i) {
                // avoid duplication
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue;
                }
                int target = 0 - nums[i];
                    
                int low = i + 1;
                int high = nums.size() - 1;
                while (low < high) {
                    if (nums[low] + nums[high] == target) {
                        //avoid duplication
                        if ((low > i + 1 && nums[low] == nums[low -1]) ||
                            (high < nums.size() - 1 && nums[high + 1] == nums[high])) {
                            low++;
                            high--;
                            continue;
                        }
                        
                        low++;
                        high--;
                        
                        results.push_back({nums[i], nums[low - 1], nums[high + 1]});
                    } else if (nums[low] + nums[high] < target) {
                        low++;
                    } else {
                        high--;
                    }
                }
            }
            return results;
        }
    };
    

Log in to reply
 

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