leetcode 18. 四数之和

题目描述

leetcode 15. 三数之和用同样的方法。有两个注意点。

一是剪枝的逻辑

这是和15. 三数之和 - 力扣(LeetCode)问题不同的地方。

无法通过这种情况:

二是整数溢出

最终答案

cpp 复制代码
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int len = nums.size();
        int left = 0;
        int right = 0;
        vector<vector<int>> res;
        for(int i = 0;i <len;i++){
            if(nums[i]>0 && nums[i]>=target)
                break;
            if(i>0&&nums[i-1]==nums[i])
                continue;
            for(int j=i+1;j <len;j++){
                if(nums[j]>0 && nums[i]+nums[j] >= target)
                    break;
                if(j>i+1 && nums[j-1]==nums[j])
                    continue;
                left=j+1;
                right=len-1;
                while(left<right){
                    if((long)nums[i]+nums[j]+nums[left]+nums[right] == target){
                        res.push_back({nums[i],nums[j],nums[left],nums[right]});
                        while(left<right-1&&nums[left]==nums[left+1]) left++;
                        while(left<right-1&&nums[right]==nums[right-1]) right--;
                        left++;
                        right--;
                    }
                    else if((long)nums[i]+nums[j]+nums[left]+nums[right] > target){
                        right--;
                    }else{
                        left++;
                    }
                }
            }
        }
        return res;
    }
};
相关推荐
sin_hielo8 小时前
leetcode 1611
算法·leetcode
来荔枝一大筐9 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
小白程序员成长日记11 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白11 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
小白程序员成长日记12 小时前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
他们叫我一代大侠13 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
海琴烟Sunshine14 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
一只鱼^_17 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
夏鹏今天学习了吗20 小时前
【LeetCode热题100(64/100)】搜索旋转排序数组
算法·leetcode·职场和发展
alphaTao21 小时前
LeetCode 每日一题 2025/11/3-2025/11/9
windows·leetcode