llllmz

导航

18. 四数之和

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ans;
        sort(nums.begin(), nums.end());
        long sum = 0;
        for(int k = 0; k < nums.size(); ++k){
            if(k > 0 && nums[k] == nums[k - 1]) continue;
            if(nums[k] > target && nums[k] > 0) break; 
            for(int i = k + 1; i < nums.size(); ++i){
                if(i > k + 1 && nums[i] == nums[i - 1]) continue;
                if(nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) break;
                int left = i + 1;
                int right = nums.size() - 1;
                while(left < right){
                    sum = (long)nums[k] + nums[i] + nums[left] + nums[right];
                    if(sum > (long)target){
                        --right;
                    }else if(sum < (long)target){
                        ++left;
                    }else{
                        ans.push_back(vector<int>{nums[k], 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-13 23:00  神奇的萝卜丝  阅读(3)  评论(0编辑  收藏  举报