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. Centos7yum安装LNMP

    (1)安装nginx 0.关闭防火墙 systemctl stop firewald.service systemctl disable firewald.service 1.使用nginx官方提供的 ...

  2. 25、Flask实战第25天:项目结构搭建

    创建一个虚拟环境bbs,并安装flask框架 #cmd进入DOS窗口 mkvirtualenv bbs pip install flask 在本地磁盘D新建项目目录:bbs 打开pycharm,创建f ...

  3. [BZOJ4765]普通计算姬(分块+树状数组)

    4765: 普通计算姬 Time Limit: 30 Sec  Memory Limit: 256 MBSubmit: 1725  Solved: 376[Submit][Status][Discus ...

  4. 【搜索】【约数个数定理】[HAOI2007]反素数ant

    对于任何正整数x,其约数的个数记作g(x).例如g(1)=1.g(6)=4.如果某个正整数x满足:g(x)>g(i) 0<i<x,则称x为反质数. 所以,n以内的反质数即为不超过n的 ...

  5. 十一. 图形、图像与多媒体5.Graphics2D类的绘图方法

    Java语言在Graphics类提供绘制各种基本的几何图形的基础上,扩展Graphics类提供一个Graphics2D类,它拥用更强大的二维图形处理能力,提供.坐标转换.颜色管理以及文字布局等更精确的 ...

  6. 关于applicationContext.xml cannot be opened because it does not exist的解决

    初学Spring在用Resource rs=new ClassPathResource("applicationContext.xml");时老是遇到这个错误.后来发现用 Appl ...

  7. WebService基于SoapHeader实现安全认证(二)

    支持通过Http请求方法调用webservice,同时支持SoapHeader验证. using Globalegrow.Common; using Globalegrow.Model; using ...

  8. uboot如何检测XC2440是从Nand或Nor启动

    转:http://blog.chinaunix.net/uid-22030783-id-3347621.html 在XC2440开发板上做uboot从nandflash启动时,需要检测硬件启动方式,启 ...

  9. 认识udev

    转:http://www.360doc.com/content/11/0415/21/1317564_109923795.shtml 因为本身从事存储行业,在工作中多次碰到用户有这样的要求:我的lin ...

  10. SQL Server 2008数据库备份和还原(还原是必须有完整备份)

    转自lwccc, SQLserver2008数据库备份和还原问题(还原是必须有完整备份) 首先,我要说明的是你必须拥有完整的数据库备份,下面的还原教程,才算有用. 这个连接是某高手的异常恢复方法, 实 ...