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;
    }
};
相关推荐
白白白小纯5 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
圣保罗的大教堂8 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
alphaTao10 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
Hi李耶17 小时前
【LeetCode】9-回文数
算法·leetcode·职场和发展
海绵天哥20 小时前
LeetCode Hot 100 | 链表(下)· 分组翻转与设计(C++ 题解)
c++·leetcode·链表
tkevinjd1 天前
力扣131-分割回文串
算法·leetcode·深度优先
zander2582 天前
LeetCode 78. 子集
算法·leetcode·深度优先
Tisfy2 天前
LeetCode 3014.输入单词需要的最少按键次数 I:遍历 / if-else计算(比纯数学公式写起来麻烦但好想)
数学·算法·leetcode·字符串·题解·贪心
tkevinjd2 天前
力扣239-滑动窗口最大值
算法·leetcode·职场和发展
圣保罗的大教堂2 天前
leetcode 628. 三个数的最大乘积 简单
leetcode