3Sum

题目

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)

• Thesolutionsetmustnotcontainduplicatetriplets.

For example, given array S = {-1 0 1 2 -1 -4}.
A solution set is:
(-1, 0, 1)
(-1, -1, 2)

思路

先对数组进行非递减排序, 确定一个数i,在对其后面的序列使用 左右游标p,q夹逼(PS:这个词确实有点)。
对num[i],num[p],num[q]三者的和sum 进行推断。 假设 sum>target: q--; 去重;
假设 sum<target: p++; 去重;
假设 sum==target: 返回结果; 去重;

这个算法的时间复杂度为O(n^2).

去重技巧:

  1. 假设num[i] = num[i - 1],说明刚才i-1时求的解在这次肯定也会求出一样的,所以直接跳过不求;
  2. 事实上指针p不须要从数组头開始,由于假设num[i]所在的解中假设有i之前的数。设其位置为j,那么我们求num[j]时,肯定把num[i]

    也找出来放到和num[j]一起的解里了,所以指针p事实上应该从i+1開始。即初始时p = i + 1, q = num.size() - 1;
  3. 当sum == 0,我们保存了当前解以后,须要num[i]在解中的其它的2个数组合,这个时候。肯定是p往后或者q往前。假设++p,发

    现事实上num[p] == num[p-1],说明这个解肯定和刚才反复了,再继续++p。

    同理,假设–q后发现num[q] == num[q+1],继续–q。

    这个去重操作主要针对这样的有多个同值的数组,如:-3, 1,1,1, 2,2,3,4。

C++代码

#include <iostream>
#include <vector> using namespace std; 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());
printf("size: %d\n", num.size()); for (int i=0; i<num.size(); ++i){
if(i!=0 && num[i]==num[i-1]) continue; int p = i+1, q = num.size()-1;
int sum = 0;
while(p < q){
sum = num[i]+num[p]+num[q];
if(sum<0){
++p;
while(num[p]==num[p-1] &&p<q) ++p;
}else if(sum>0){
--q;
while(num[q]==num[q+1] &&p<q) --q;
}else{
printf("%d, %d, %d",num[i], num[p], num[q]);
//result.push_back({num[i], num[p], num[q]});
vector<int> newRes;
newRes.push_back(num[i]);
newRes.push_back(num[p]);
newRes.push_back(num[q]);
result.push_back(newRes); while(++p<q && num[p]==num[p-1]){
//do nothing
}
while(--q>p && num[q]==num[q+1]){
//do nothing
}
}
}
}
return result;
}
}; int main(int argc, char *argv[]) {
int a[] = {-1,0,1};
vector<int> v(&a[0],&a[3]);
Solution s;
vector<vector<int> > result = s.threeSum(v); }

3Sum Closet

再补充其相关题,思路是一样的。直接上代码:

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result;
int min_gap = INT_MAX;
sort(nums.begin(), nums.end()); for(int i=0; i<nums.size(); ++i){
int p = i+1;
int q = nums.size()-1; while(p < q){
int sum = nums[i] + nums[p] + nums[q];
int gap = abs(sum-target); if(gap < min_gap){
result = sum;
min_gap = gap;
} if(sum < target){
++p;
}else{
--q;
}
}
}
return result;
}
};

LeetCode——3Sum &amp; 3Sum Closest的更多相关文章

  1. LeetCode:15. 3Sum(Medium)

    1. 原题链接 https://leetcode.com/problems/3sum/description/ 2. 题目要求 数组S = nums[n]包含n个整数,请问S中是否存在a,b,c三个整 ...

  2. LeetCode(15)题解--3Sum

    https://leetcode.com/problems/3sum/ 题目: Given an array S of n integers, are there elements a, b, c i ...

  3. 【LeetCode】15. 3Sum 三数之和

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

  4. 乘风破浪:LeetCode真题_016_3Sum Closest

    乘风破浪:LeetCode真题_016_3Sum Closest 一.前言      这一次,问题又升级了,寻找的是三个数之和最靠近的某个数,这是非常让人难以思考的,需要把三个数相加之后和最后给的目标 ...

  5. [LeetCode][Python]16: 3Sum Closest

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 16: 3Sum Closesthttps://oj.leetcode.com ...

  6. 【LeetCode】16. 3Sum Closest 最接近的三数之和

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

  7. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  8. 《LeetBook》leetcode题解(16):3Sum Closest [M]

    我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...

  9. LeetCode OJ:3Sum Closest(最接近的三数之和)

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

  10. Leetcode Array 16 3Sum Closest

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

随机推荐

  1. 魔法上网之Ubuntu部署“酸酸”

    “酸酸”,即s*h*a*d*o*w*s*o*c*k*s,用于魔法上网,用python写成. 在ubuntu环境下,用pip包管理工具可以非常方便地安装“酸酸”服务:ssserver. 先安装pip(假 ...

  2. PHP PDO类 单例

    <?php /*//pdo连接信息 $pdo=array("mysql:host=localhost;dbname=demo;charset=utf8","root ...

  3. (5) go 控制台输入输出、进制转换、原反补码、位运算

    一.控制台接受输入 二.原反补码 三.位运算 四.移位运算

  4. POJ 1182 食物链 【带权并查集/补集法】

    动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形.A吃B, B吃C,C吃A. 现有N个动物,以1-N编号.每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种.有人用两种说 ...

  5. go chapter 1

    case 1 // helloworld.go package main import "fmt" func main() { fmt.Println("Hello, 世 ...

  6. Noip2015提高组解题报告

    Day1 T1神奇的幻方 一道简单异常的小模拟,我们只需要确定数字1的位置,然后根据题意枚举即可,简简单单就A了,什么也不卡. 然而这题,我刚开始学OI的时候,因为当时比较蠢,被这题花式吊打啊.... ...

  7. 【js学习】js连接RabbitMQ达到实时消息推送

    js连接RabbitMQ达到实时消息推送 最近在自己捯饬一个网站,有一个功能是需要后端处理完数据把数据发布到MQ中,前端再从MQ中接收数据.但是前端连接MQ又成了一个问题,在网上搜了下资料,点进去一篇 ...

  8. 【UOJ #201】【CTSC 2016】单调上升路径

    http://uoj.ac/problem/201 别人都一眼秒的题对我而言怎么那么难qwq 这道题就是要构造一个n*n的邻接矩阵,满足矩阵\(A\)是一个拉丁方阵(也是数独?),\(a_{ij}=a ...

  9. HDU 6060 RXD and dividing(LCA)

    [题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6060 [题目大意] 给一个n个节点的树,要求将2-n号节点分成k部分, 然后将每一部分加上节点1, ...

  10. BZOJ 1305 [CQOI2009]dance跳舞(二分+网络流)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1305 [题目大意] 一次舞会有n个男孩和n个女孩. 每首曲子开始时,所有男孩和女孩恰好 ...