题解 | #双指针——三数之和#

三数之和

https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

#include <algorithm>
#include <vector>
class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int>> ans;
        if(num.size() < 3) return ans;
        sort(num.begin(), num.end());
        for(int i=0;i<num.size()-2;i++){
            if(i!=0&&num[i] == num[i-1]) continue; //去重
            int left = i+1;
            int right = num.size() - 1;
            int target = -num[i];
            while (left < right) {
                if(num[left] + num[right] == target){
                    ans.push_back({num[i],num[left],num[right]});
                    while (left+1 < right && num[left] == num[left+1]) {
                        left++;//去重
                    }
                    while (right - 1 > left && num[right] == num[right-1]) {
                        right--;//去重
                    }
                    left++;
                    right--;
                }
                else if (num[left] + num[right] > target) {
                    right--;
                }
                else 
                    left++;
            }
        }
        return ans;
    }
};

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务