llllmz

导航

15. 三数之和

practise makes perfect! 相信自己的努力不会白费,继续学习吧

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < nums.size(); ++i){
            if(nums[i] > 0) return ans;
            if(i > 0 && nums[i] == nums[i -1]) continue;
            int left = i + 1;
            int right = nums.size() - 1;
            while(left < right){
                if(nums[i] + nums[left] + nums[right] > 0){
                    --right;
                }else if(nums[i] + nums[left] + nums[right] <0){
                    ++left;
                }else{
                    ans.push_back(vector<int>{nums[i], nums[left], nums[right]});
                    while(left < right && nums[left] == nums[left + 1]) ++left; 
                    while(left < right && nums[right] == nums[right -1]) --right;
                    ++left;
                    --right;
                }
            }
        }
        return ans;
    }
};

 

posted on 2024-10-12 19:45  神奇的萝卜丝  阅读(2)  评论(0编辑  收藏  举报