Mark, C++ solution


  • 0
    X
    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            if (nums.size() <= 2) {
                vector<vector<int> > nullVector; return nullVector;
            }
            
            sort(nums.begin(), nums.end());
            vector<vector<int> > res;
            
            long previous = LONG_MAX;
            for (int i = 0; i < nums.size() - 2; i++) {
                int target = -nums[i];
                if (target == previous) continue;
                int first = i + 1, last = nums.size() - 1;
                while (first < last) {
                    if (nums[first] + nums[last] == target) {
                        res.push_back(vector<int> {-target, nums[first], nums[last]});
                        while (first < nums.size() && nums[first] == nums[first + 1]) first++;
                        while (last > i && nums[last] == nums[last - 1]) last--;
                        first++; last--;
                    } else if (nums[first] + nums[last] < target) {
                        first++;
                    } else if (nums[first] + nums[last] > target) {
                        last--;
                    }
                }
                
                previous = target;
            }
            
            return res;
        }
    };

Log in to reply
 

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