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. 辨析各类web服务器:Apache/Tomcat/Jboss/Nginx/等,还有Nodejs

    先说一下各类服务器能干啥,特点是啥,然后在区分他们的类别. (1)Apache: Apache是指Apache软件基金会的Apache HTTP Server, 它能够接收http请求,然后返回各类资 ...

  2. 微信小程序-二维码汇总

    小程序二维码在生活中的应用场景很多,比如营销类一物一码,扫码开门,扫码付款等...小程序二维码分两种? 1.普通链接二维码 即跟普通的网站链接生成的二维码是一个意思,这种二维码的局限性如下: 对于普通 ...

  3. git冲突解决的方法

    在运行时,出现了冲突的报错.类似于<<<<<<< HEAD,在你改变的文件有分支与HEAD间的区别.这里就是冲突的地方. 1.解决方法一 使用命令  切换分支 ...

  4. 在centos 6.9安装wordpress,浏览器不能访问问题

    在centos 6.9安装wordpress浏览器访问先出现403错误,然后提示access denied nginx错误打印FastCGI sent in stderr: "Unable ...

  5. 洛谷P3941入阵曲

    题目传送门 这道题也是今年湖南集训队Day8的第一题,昨天洛谷的公开赛上又考了一遍,来发个记录(其实是因为五月天,另外两道题分别是将军令和星空,出这次题目的人肯定同为五迷(✪㉨✪)) 话不多说.先理解 ...

  6. Flask实战第39天:完成前台注册界面

    在template下创建目录front,该目录用于存放前台页面的所有模板 在front下创建登录模板 <!DOCTYPE html> <html lang="en" ...

  7. hdu 1011(Starship Troopers,树形dp)

    Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...

  8. JavaScript的程序构成

    JavaScript的程序构成主要从以下几方面做个总结:控制语句.函数 .事件驱动及事件处理,希望对读者有些帮助. 控制语句: if条件语句 基本格式 if(表述式) 语句段1: ...... els ...

  9. NOIP 2006 提高组 t1 能量项链

    题目描述 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾标记的珠子,这些标记对应着某个正整数.并且,对于相邻的两颗珠子,前一颗珠子的尾标记一定 ...

  10. ARC-100 E - Or Plus Max

    题面在这里! 我们如果可以求出 f[x] = max{ a[i] + a[j] , i!=j && i or j == x},那么就可以通过前缀max直接递推答案了. 但是这个玩意不是 ...