[LeetCode] 3Sum 三数之和

时间:2022-11-06 19:08:06

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
(-1, 0, 1)
(-1, -1, 2)

这道题让我们求三数之和,比之前那道 Two Sum 要复杂一些,博主考虑过先 fix 一个数,然后另外两个数使用 Two Sum 那种 HashMap 的解法,但是会有重复结果出现,就算使用 TreeSet 来去除重复也不行,会 TLE,看来此题并不是考 Two Sum 的解法。来分析一下这道题的特点,要找出三个数且和为0,那么除了三个数全是0的情况之外,肯定会有负数和正数,还是要先 fix 一个数,然后去找另外两个数,只要找到两个数且和为第一个 fix 数的相反数就行了,既然另外两个数不能使用 Two Sum 的那种解法来找,如何能更有效的定位呢?我们肯定不希望遍历所有两个数的组合吧,所以如果数组是有序的,那么就可以用双指针以线性时间复杂度来遍历所有满足题意的两个数组合。

对原数组进行排序,然后开始遍历排序后的数组,这里注意不是遍历到最后一个停止,而是到倒数第三个就可以了。这里可以先做个剪枝优化,就是当遍历到正数的时候就 break,为啥呢,因为数组现在是有序的了,如果第一个要 fix 的数就是正数了,则后面的数字就都是正数,就永远不会出现和为0的情况了。然后还要加上重复就跳过的处理,处理方法是从第二个数开始,如果和前面的数字相等,就跳过,因为不想把相同的数字fix两次。对于遍历到的数,用0减去这个 fix 的数得到一个 target,然后只需要再之后找到两个数之和等于 target 即可。用两个指针分别指向 fix 数字之后开始的数组首尾两个数,如果两个数和正好为 target,则将这两个数和 fix 的数一起存入结果中。然后就是跳过重复数字的步骤了,两个指针都需要检测重复数字。如果两数之和小于 target,则将左边那个指针i右移一位,使得指向的数字增大一些。同理,如果两数之和大于 target,则将右边那个指针j左移一位,使得指向的数字减小一些,代码如下:

解法一:

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
if (nums.empty() || nums.back() < || nums.front() > ) return {};
for (int k = ; k < (int)nums.size() - ; ++k) {
if (nums[k] > ) break;
if (k > && nums[k] == nums[k - ]) continue;
int target = - nums[k], i = k + , j = (int)nums.size() - ;
while (i < j) {
if (nums[i] + nums[j] == target) {
res.push_back({nums[k], nums[i], nums[j]});
while (i < j && nums[i] == nums[i + ]) ++i;
while (i < j && nums[j] == nums[j - ]) --j;
++i; --j;
} else if (nums[i] + nums[j] < target) ++i;
else --j;
}
}
return res;
}
};

或者我们也可以利用 TreeSet 的不能包含重复项的特点来防止重复项的产生,那么就不需要检测数字是否被 fix 过两次,不过个人觉得还是前面那种解法更好一些,参见代码如下:

解法二:

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
set<vector<int>> res;
sort(nums.begin(), nums.end());
if (nums.empty() || nums.back() < || nums.front() > ) return {};
for (int k = ; k < (int)nums.size() - ; ++k) {
if (nums[k] > ) break;
int target = - nums[k], i = k + , j = (int)nums.size() - ;
while (i < j) {
if (nums[i] + nums[j] == target) {
res.insert({nums[k], nums[i], nums[j]});
while (i < j && nums[i] == nums[i + ]) ++i;
while (i < j && nums[j] == nums[j - ]) --j;
++i; --j;
} else if (nums[i] + nums[j] < target) ++i;
else --j;
}
}
return vector<vector<int>>(res.begin(), res.end());
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/15

类似题目:

Two Sum

3Sum Smaller

3Sum Closest

4Sum

参考资料:

https://leetcode.com/problems/3sum/

https://leetcode.com/problems/3sum/discuss/7380/Concise-O(N2)-Java-solution

https://leetcode.com/problems/3sum/discuss/7373/Share-my-simple-java-solution

http://www.lifeincode.net/programming/leetcode-two-sum-3-sum-3-sum-closest-and-4-sum-java/

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 3Sum 三数之和的更多相关文章

  1. 【LeetCode】15&period; 3Sum 三数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, 三数之和,题解,leetcode, 力扣,P ...

  2. LeetCode:三数之和【15】

    LeetCode:三数之和[15] 题目描述 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的 ...

  3. &lbrack;LeetCode&rsqb; 15&period; 3Sum 三数之和

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  4. LeetCode 15&period; 三数之和&lpar;3Sum&rpar;

    15. 三数之和 15. 3Sum 题目描述 Given an array nums of n integers, are there elements a, b, c in nums such th ...

  5. 【LeetCode】三数之和【排序,固定一个数,然后双指针寻找另外两个数】

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  6. Java实现 LeetCode 15 三数之和

    15. 三数之和 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以 ...

  7. &lbrack;Leetcode&rsqb; 3sum 三数和

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  8. LeetCode——15&period; 三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  9. LeetCode 15&period; 三数之和(3Sum)

    题目描述 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复 ...

随机推荐

  1. text-align&equals;center 失效原因

    text-align属性是针对 内联元素居中得属性设置,对于块状元素使用margin:0 auto;来控制居中: 笔者在设置一个h2标签时设置了text-align:center;但是却始终出现在中间 ...

  2. PKU 1001解题代码

    本来以前也写过,但是由于许多细节问题,没有AC,今天修改了一下,终于AC了,以前没有AC的具体原因总结了了一下,必须任何数的0次方都等于1没有考虑,还有就是首0和末尾0以及小数点没有处理好,下面贴代码 ...

  3. MIME Type

    一.首先,我们要了解浏览器是如何处理内容的.在浏览器中显示的内容有 HTML.有 XML.有 GIF.还有 Flash --那么,浏览器是如何区分它们,决定什么内容用什么形式来显示呢?答案是 MIME ...

  4. java基础学习总结——基础语法1

    一.标识符

  5. ✡ leetcode 158&period; Read N Characters Given Read4 II - Call multiple times 对一个文件多次调用read(157题的延伸题) --------- java

    The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actu ...

  6. &lbrack;LeetCode101&rsqb;Symmetric Tree

    题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). F ...

  7. wtforms快速使用和源码分析&lpar;基于flask&rpar;

    wtforms 和django的form组件大同小异,下面给出一个应用举例以便快速查询. 开始使用 from flask import Flask, render_template, request, ...

  8. SpriteBuilder中音频文件格式的需要注意的地方

    就像在SpriteBuilder项目子目录中的其他资源文件一样,音频文件夹需要确定完整的文件夹路径. 并且如果音频文件输出格式为MP4,则扩展为.m4a(audio-only MPEG4)而不是.mp ...

  9. HTTL之初印象

    概述 HTTL (Hyper-Text Template Language) 是一个高性能的开源JAVA模板引擎, 适用于动态HTML页面输出, 可替代JSP页面, 指令和Velocity相似. 简洁 ...

  10. PowerDesigner使用积累

    PowerDesigner想必没人不知道吧?著名的CASE工具,目前最新版本为15.2,用于软件建模,可以从需求直到物理模型,支持UML2.0语法,可用于UML图绘制.最大特色是能够使设计到实现无缝衔 ...