Given an array S of n integers, are there elements a, b, c 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)

分析:

这道题原本不难,但是题目要求结果不能够包含重复的 triplets, 往往容易出错。

思路1:

step 1: 先排序

step 2:   枚举前两个数,如果要满足 sum = 0, 那么第三个数必须是 前两个数和的负数。

通过二分搜索去查找。。复杂度 是 O(N^2 * lgN)

思路2:

O(N^2)的算法。

借助于 2 sum的思路:如果在一个已经排序的数组中,寻找两个数的和为给定的sum, 其实有 O(N)的算法。

指针 i, j  分别指向数组的首尾,如果 num[i] + num[j] < 0, 则 i++;  如果 > 0, j--; 直到和等于sum.

因此,本题可以

step 1:   排序

step 2:  先枚举第一个数,然后在排好序的数组中寻找 两个数和等于 第一个数的负数。

Note: 为了避免重复的 triplets, 有一些小细节需要考虑。具体见下面的代码。

基本的思想就是 如果碰到相邻的数相同,可以跳过。

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
if(num.size() < 3) return result; sort(num.begin(), num.end()); //处理以num[k]开头的和
for(int k=0; k<num.size()-2; ++k){
if(k > 0 && num[k] == num[k-1]) continue; //避免重复 int i=k+1, j=num.size()-1; //分别指向首尾
while(i < j){
if(i > k+1 && num[i] == num[i-1]){
++i;
continue;
}
if(j < num.size()-1 && num[j] == num[j+1]){
--j;
continue;
} if(num[k] + num[i] + num[j] < 0)
++i;
else if(num[k] + num[i] + num[j] > 0)
--j;
else{
result.push_back(vector<int>{num[k], num[i++], num[j--]});
}
}
} return result;
}
};

LeetCode----3 Sum的更多相关文章

  1. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  2. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  5. [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  6. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  7. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  8. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  9. [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  10. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

随机推荐

  1. var isObj = length === undefined || i

    这个其实是因为你前面那个===是肯定为false导致的,所以执行到了i那一步了var length=undefined;var a=length===undefined || i;这样你不定义i也是不 ...

  2. [转]用Python读写Excel文件

    [转]用Python读写Excel文件   转自:http://www.gocalf.com/blog/python-read-write-excel.html#xlrd-xlwt 虽然天天跟数据打交 ...

  3. ie6 ie7 绝对定位 相对定位 层被遮住

    relative 上加上z-index有多个,则z-index递减, absolute层显示则不会被其它标签挡住.

  4. SVN clean up问题

    问题如截图所示: 解决方法:在根目录clean up,注意把所有的选项都勾上

  5. POJ 3206 最小生成树

    DESCRIPTION:T_T 在下是读不懂题意的.但是捏.现在知道是求把所有的点(是字母的点)连起来的最小的权值.即最小生成树.因为求最小生成树是不计较源点是哪个的.所以可以把A和S看成一样的.首先 ...

  6. SqlServer 慢查询分析优化

    分三步: 记录慢查询的语句到日志文件 1.首先在SSMS,工具菜单下打开Profiler. 2.输入你用户名密码登陆. 3.常规,勾选保存到文件,选择一个文件路径,设置文件大小,这样可以分文件存储日志 ...

  7. a标签的css样式四个状态的设计

    表示所有状态下的连接 如 a{color:red} ① a:link:未访问链接 ,如 a:link {color:blue} ② a:visited:已访问链接 ,如 a:visited{color ...

  8. C char** 的一点儿理解

    理解是就是char** 相当于字符串数组,我以往纠结于该用 **arr还是*arr还是 (*arr),还是(**arr): 对于**arr而言:*arr代表数组的最开头,也就是第一个字串的内容.**a ...

  9. C#获取指定日期为一年中的第几周

    /// <summary> /// 获取指定日期,在为一年中为第几周 /// </summary> /// <param name="dt">指 ...

  10. git初识

    下载网上的开发员的项目 git clone https://github.com/xxxxxx/test.git 下载好,进入刚下载的好的test项目目录,可以修改对应的代码,然后 git statu ...