Leetcode-18: 4Sum

Leetcode | C++ 18.4Sum 题意 中文描述 给定一个数列 S ,包含 n 个整数.在 S 中找到四个元素 a, b, c, d 使得 a + b + c + d = target . 找到所有的独特的满足上述条件的四元组. 注意: 结果集包含的四元组不重复. 题解 算法及复杂度(45 ms) 本题与第 15 题 (3Sum) 比较类似,第 15 题是求三个数的和,本题是求四个数的和.建议先去练习第 15 题. 首先,为了避免结果的重复,先对数列进行排序.依照在 15 题中提到的: 在一段数列上找到和为固定值的两个数的复杂度可以为 O( 阅读详情
  1. 4Sum
    Medium

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Notice that the solution set must not contain duplicate quadruplets.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:

Input: nums = [], target = 0
Output: []

Constraints:

0 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109

解法1:跟3Sum差不多。时间复杂度O(n^3),因为3sum时间复杂度是O(n ^2), 2sum时间复杂度是O(n)。
代码如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>

using namespace std;

vector<vector<int>> fourSum(vector<int>& nums, int target) {
    vector<vector<int>> vv;
    if (nums.size()<4) return vv;

    sort(nums.begin(), nums.end());

    set<vector<int> > s;

    for (int i=0; i<nums.size()-3; ++i) {
        for (int j=i+1; j<nums.size()-2; ++j) {
            int diff2 = target-nums[i]-nums[j];
            int p1=j+1, p2=nums.size()-1;
            while(p1<p2) {
                int sum = nums[p1]+nums[p2];
                if (sum<diff2) p1++;
                else if (sum>diff2) p2--;
                else {
                     s.insert(vector<int>{nums[i], nums[j], nums[p1], nums[p2]});
                     p1++; p2--;   //do not directly break as there may be some other solutions left.
                }
            }
        }
    }

    for (auto it=s.begin(); it!=s.end(); ++it)   //note: should not use it<s.end() as set does not provide operator<
        vv.push_back(*it);

    return vv;
}

int main()
{
    //vector<int> S={1, 0, -1, 0, -2, 2};
    vector<int> S={-3,-2,-1,0,0,1,2,3};
    vector<vector<int> > vv;

    vv=fourSum(S, 0);

    cout<<"["<<endl;
    for (auto i : vv) {
        cout<<" [ ";
        for (auto j : i) cout<<j<<" ";
        cout<<"],"<<endl;
    }
    cout<<"]"<<endl;
    return 0;
}

要注意的地方有:

  1. 当找到一个解后,不要直接退出,还要p1++,p2–。因为可能还有其他解。
  2. set的iterator不支持operator<,只能用!=。这可能跟set内部是用RB tree有关,没法用<来判断。

解法2:把nums的元素两两相加,并记录(sum, pair(i, j)),这样就可以构成一个长度为n2n^2n2的数组,然后就可以直接用2sum了。时间复杂度是O(n2)O(n^2)O(n2)。下次做。

手把手教你如何修改YOLO11的模型结构(以CBAM和可变性卷积为例) YOLO11修改模型结构 阅读详情

相关推荐

SAP销售订单POD实操:从VL01N创建到VLPOD差异处理,保姆级避坑指南

本文详细解析SAP销售订单POD全流程,从VL01N创建到VLPOD差异处理,提供保姆级避坑指南。涵盖核心业务逻辑、前置配置、销售订单创建、交货单处理及差异解决方案,帮助用户高效管理供应链执行环节,确保财务与物流的准确对接。

weixin_27219587的博客 634

LeetCode-18. 4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of tar...

reigns的博客 191

YF-S401水流量传感器在STM32上的精准计量实现

本文详细介绍了YF-S401水流量传感器与STM32微控制器的集成应用,实现精准水流计量。通过外部中断和外部时钟两种脉冲计数方案,结合硬件配置、软件滤波和校准技巧,确保高精度流量测量。适用于智能家居和工业自动化中的水控系统,提升系统稳定性和测量准确性。

rainy的博客 902

(Java)LeetCode-18. 4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Element

u012848330的博客 1854

Windows音效增强设置详解:从系统开关到专业EQ调音

声音信号在Windows系统中需要经过混音器、声卡驱动与APO效果器等多层处理链路,最终才到达耳机或音箱。系统自带的响度均衡、低音增强、虚拟环绕等音频增强选项,本质上是对动态范围和频响的干预,理解其原理才能避免盲目开启导致声音发闷或失真。空间音效与采样率的正确配置,可减少SRC重采样带来的音质损失,而Win11的音频增强开关和通信设置也常被忽视。无论是板载声卡还是USB解码耳放,合理利用系统增强和Equalizer APO等工具,都能显著改善听感体验。本文结合场景给出设置建议,帮助用户告别声音浑浊,获得干净

weixin_31155097的博客 442

企业微信消息推送API实战:5步搞定可信IP与域名配置(含Python代码示例)

本文详细解析了企业微信消息推送API实战中的关键配置步骤,特别是可信IP与可信域名的配置流程。通过5个清晰步骤,结合Python代码示例,指导开发者快速完成安全通信链路搭建,避免常见错误,确保消息推送服务稳定可靠。

qsc9012345的博客 1010

leetcode-Java-18. 4Sum

public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<List<Integer>>(); int len = nums.length, to

王欢的博客 886

ZYNQ-Video out IP与Video Timing Controller IP协同工作模式解析

本文深入解析了ZYNQ平台上Video out IP与Video Timing Controller IP的协同工作模式,详细介绍了它们的架构、工作原理及配置要点。通过AXI4-Stream接口实现高效视频数据传输,并结合HDMI输出系统设计实践,为开发者提供了实用的调试技巧和性能优化建议。

redis7keeper的博客 639

LeetCode第18题:四数之和(JAVA实现)

题目: 我的解答: public List&lt;List&lt;Integer&gt;&gt; fourSum(int[] nums, int target) { Arrays.sort(nums); List&lt;List&lt;Integer&gt;&gt; res=new ArrayList&lt;&gt;(); for(int i=0;i&lt;nums.leng...

FaustoPatton的博客 882

llama-factory微调qwen2.5-vl

使用llama-factory完成qwen2.5-vl微调

qq_44908396的博客 2938

Android Framework AMS面试题及参考答案

比如,应用 B 的 Activity 如果是 “singleTask” 启动模式,AMS 会查找应用 B 是否有包含该 Activity 的任务栈,若有则将这个任务栈切换到前台,并且清除该 Activity 之上的其他 Activity,实现流畅的跨应用跳转体验。如果一个 Activity 的启动依赖于另一个 Activity 的结果,AMS 会暂停当前 Activity 的部分生命周期操作,等待依赖的 Activity 完成相关操作后,再继续当前 Activity 的生命周期进程。

大模型大数据攻城狮的专栏 1873

LeetCode 18. 四数之和(C++)

题目: 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。 示例: 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求...

my_clear_mind的博客 1347

硬件学习手册【总目录】

欢迎大家来到《硬件学习手册》,专栏主要包括 《硬件经验手册》《电子元器件器件手册》《PCB手册》《CPU手册》《元器件选型手册》五个分册。在开始专栏的更新前,博主先列出专栏的大纲,以供大家参考。大家直接点击大纲中的蓝色标题即可轻松传送。

fydar的博客 5890

leetcode 18. 4Sum

''' 给定输入数组,输出4元对列表,列表中每个元素是一个列表,子列表数值之和为target ''' class Solution: def fourSum(self, nums, target: int): def select_sort(nums): # 对输入数据进行选择排序 # 选择排序算法是对冒泡排序算法的改进 ...

WYXHAHAHA123的博客 208

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LeetCode 力扣:15.3Sum + 16.3Sum Closest + 18.4Sum 排序 + 双指针遍历 题目+算法分析+Cpp解答

15.3Sum 排序 + 双指针遍历: ​ 首先,将给定的数组进行排序(从小到大的顺序)。 ​ 遍历排序后的数组中的每一个数,如果这个数之前已经讨论过了则可以跳过。 ​ 将取出的数作为“目标”,使用双指针在排序后的数组中找另外的两个数: ​ 一个左指针指向该取出的数的后一个数,即此时的最低位。 ​ 另一个右指针指向数组的最后一个数,即此时的最高位。 ​ 由于数组已经是从小到...

WULH 1177

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

leetcode 18:4Sum

class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ length = len(nums)...

dxcve的博客 178

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode: 18. 4Sum

题目: LeetCode:18. 4Sum 描述: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of ...

dbb191379的博客 182

leetcode 18 4Sum 详细解答

leetcode 18 4Sum 详细解答 代码如下:

qq_22210659的博客 205

leetcode18 4Sum

题目描述 Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum o...

yaotai8135的博客 166

【leetcode】18. 4Sum

题目: Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of...

zxc120389574的博客 93

LeetCode //C - 18. 4Sum

【代码】LeetCode //C - 18. 4Sum。

Made in Code 977

LeetCode 18. 4Sum

问题链接 LeetCode 18. 4Sum 题目解析 给定n元素的数组,求出满足 \(a+b+c+d = target\) 的所有元组。 解题思路 已经成为一个系列了,这道题是 LeetCode 15. 3Sum 的升级版,思路与其也是一模一样,外层再加一层循环。 先将数组排好序,便于检测重复。最外层循环固定最小数字 \(a\),第二层循环固定第二小数字 \(b\),左右指针分别代表 \(c\)...

weixin_30547797的博客 72

LeetCode: 18. 4Sum

LeetCode: 18. 4Sum 递归调用的例子,参考网上的实现https://discuss.leetcode.com/topic/46339/my-solution-generalized-for-ksums-in-java/5 class Solution { int len =0; public List&lt...

哎呀妈呀脑壳疼脑壳疼 117

[leetcode]18. 4Sum

[leetcode]18. 4Sum Analysis 中秋节了,中午要去吃海底捞—— [嘻嘻~] Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all uniq...

weixin_32135877的博客 105

【Leetcode- 18】4Sum

【Leetcode- 18】4Sum /*Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which...

zj20165149的博客 174
上一篇: Leetcode-16: 3Sum Closest
下一篇: Leetcode-47: Permutations II
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址