YunheWang0813
10/26/2019 - 5:44 AM

0015. 3Sum

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        if (nums.empty() || nums.size() < 3) return res;
        sort(nums.begin(), nums.end());
        
        for (int i = 0; i < nums.size() - 2; i++) {
            // 跳过同样的sum
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int low = i + 1;
            int high = nums.size() - 1;
            int sum = 0 - nums[i];
            while (low < high) {
                // 对于一个sum有很多解法
                if (nums[low] + nums[high] == sum) {
                    vector<int> tmp(3);
                    tmp[0] = nums[low];
                    tmp[1] = nums[high];
                    tmp[2] = nums[i];
                    res.push_back(tmp);
                    // 跳过相同答案
                    while (low < high && nums[low] == nums[low + 1]) low++;
                    while (low < high && nums[high] == nums[high - 1]) high--;
                    low++, high--;
                }
                else if (nums[low] + nums[high] < sum) {
                    low++;
                }
                else {
                    high--;
                }
            }
        }
        return res;
    }
};