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. Ubuntu 下 Neo4j单机安装和集群环境安装

    1. Neo4j简介 Neo4j是一个用Java实现的.高性能的.NoSQL图形数据库.Neo4j 使用图(graph)相关的概念来描述数据模型,通过图中的节点和节点的关系来建模.Neo4j完全兼容A ...

  2. MySQL 存储php中json_encode格式中文问题及解决

    MySQL 存储php中json_encode格式信息  ,遇到中文时, 会变成一堆类似uxxxx信息. 1. 原因分析:在存储到数据库时!MySQL 不会存储 unicode 字符: MySQL 仅 ...

  3. cf------(round 2)A. Winner

    A. Winner time limit per test 1 second memory limit per test 64 megabytes input standard input outpu ...

  4. nyoj 115------城市平乱( dijkstra // bellman )

    城市平乱 时间限制:1000 ms  |  内存限制:65535 KB 难度:4   描述 南将军统领着N个部队,这N个部队分别驻扎在N个不同的城市. 他在用这N个部队维护着M个城市的治安,这M个城市 ...

  5. Valid Palindrome [LeetCode]

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  6. Login 页面

    1.jsp <script type="text/javascript"> function doLogin() { if (trim($('#username').v ...

  7. HTML5 视频规范简介

    HTML5 视频规范简介  创建于 2013-02-03, 周日 00:56  作者 白建鹏 HTML 一词是“超文本标记语言”(Hyper-Text Markup Language)的缩写,是用于描 ...

  8. sed 替换

    sed -i 's/i=0/i=2/g' test2.sh -i 在当前文档替换 g 替换所有文档 sed -i '3s/cccc/ccccc/' a.txt 将第三行的 cccc 替换成 ccccc ...

  9. Octopus系列之关于多选属性如何在OO中表示呢?

    在电子商务系统中 关于产品属性的问题 会设计如下几个表 产品信息        Product 选项信息表     Option        存储 Size  Color.... 选项值信息表  O ...

  10. 使用Zen coding高效编写html代码

    zen-Coding是一款快速编写HTML,CSS(或其他格式化语言)代码的编辑器插件,这个插件可以用缩写方式完成大量重复的编码工作,是web前端从业者的利器. zen-Coding插件支持多种编辑器 ...