题目

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

代码

class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
std::vector<std::vector<int> > ret_vector;
if (num.size() < )
{
return ret_vector;
}
// sort the vector
std::sort(num.begin(), num.end());
// visit all the left side element of the current element
const int target = ;
std::vector<int>::iterator end = num.end();
for (std::vector<int>::iterator i = num.begin(); i != end-; ++i){
// ignore first duplicate i
if ( i > num.begin() && *i==*(i-)) continue;
std::vector<int>::iterator j = i+;
std::vector<int>::iterator k = end-;
while (j<k){
const int tmp = *i+*j+*k;
if ( tmp < target ){
++j;
while ( *j==*(j-) && j<k ) ++j;
}
else if ( tmp > target ){
--k;
while ( *k==*(k+) && j<k ) --k;
}
else{
int tmp_triple[] = {*i,*j,*k};
std::vector<int> tmp_vector(tmp_triple,tmp_triple+);
ret_vector.push_back(tmp_vector);
++j;
--k;
while( *j==*(j-) && *k==*(k+) && j<k ) {
++j;
--k;
}
}
}
}
return ret_vector;
}
};

Tips:

1. 先对传入的vector排序,然后从前向后遍历。原则是:包含*i元素,且满足条件的triple都加入到返回结果中

2. 这里比较困难的一点是排除重复的triple,大概想一想原则,一些极端的case只能试验出来了

另,在mac上编辑的,不知道为什么用数组初始化vector编译不通过,所以采用了比较麻烦的传参方式

===============================================

第二次过这道题,大体思路记得不太清,重新学习了一下“排序+双指针夹逼”方法

参考的blog:http://www.cnblogs.com/tenosdoit/p/3649607.html

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > ret;
if ( nums.size()< ) return ret;
std::sort(nums.begin(), nums.end());
for ( int i=; i<nums.size()-; ++i )
{
// skip the duplicates elements
if ( i> && nums[i]==nums[i-] ) continue;
Solution::TwoSum(ret, nums, i+, -nums[i]);
}
return ret;
}
static void TwoSum(vector<vector<int> >& ret, vector<int>& nums, int begin, int target)
{
vector<int> tmp;
int start = begin;
int end = nums.size()-;
while ( begin<end )
{
if ( nums[begin]+nums[end]<target ){
begin++;
}
else if ( nums[begin]+nums[end]>target ){
end--;
}
else
{
// add a triple
tmp.push_back(nums[start-]);
tmp.push_back(nums[begin]);
tmp.push_back(nums[end]);
ret.push_back(tmp);
tmp.clear();
// skip the duplicate elements
begin++;
while ( begin<end && nums[begin]==nums[begin-] ) begin++;
end--;
while ( begin<end && nums[end]==nums[end+] ) end--;
}
}
}
};

tips:

1. 先对数组进行排序

2. 固定一个元素,从其后面元素开始,采用两头夹逼的方式进行遍历。(为什么要两边夹逼?因为元素已经从小到大排序好了,向后移动begin可以增加两个元素的和,向前移动end可以减小两个元素的和;采用这样的方式,相当于进可往最大和靠,退可往最小值收,可以保证不漏)

3. 如果遇到重复的元素要跳过去,因为题中要求不能出现重复的triple。

【3Sum】cpp的更多相关文章

  1. 【4Sum】cpp

    题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...

  2. 【Permutations】cpp

    题目: Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the fo ...

  3. 【Subsets】cpp

    题目: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset ...

  4. 【Anagrams】 cpp

    题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...

  5. 蓝桥杯 【dp?】.cpp

    题意: 给出一个2*n的方格,当刷完某一个方格的漆后可以且只可以走到相邻的任何一格,即上 下 左 右 左上 左下 右上 右下.可以从任意一个格子开始刷墙,问有多少种刷法,因为随着n的增大方案数会变多, ...

  6. 【Triangle 】cpp

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  7. 【N-Queens】cpp

    题目: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two que ...

  8. 【Combinations】cpp

    题目: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For ex ...

  9. 【Candy】cpp

    题目: There are N children standing in a line. Each child is assigned a rating value. You are giving c ...

随机推荐

  1. 初学者:Git常用命令总结

    git init      在本地新建一个repo,进入一个项目目录,执行git init,会初始化一个repo,并在当前文件夹下创建一个.git文件夹.   git clone      获取一个u ...

  2. python3基础01(常见语法基础汇总)

    #!/usr/bin/env python# -*- coding:utf-8 -*- # 换行\n 续行\ s[:i] + s[i:] 等于 s#转义 \e 空 \000 八进制 \oyy 十六进制 ...

  3. centos开机启动自定义脚本

    有些时候我们需要在服务器里设置一个脚本,让他一开机就自己启动.方法如下: cd /etc/init.d vi youshell.sh #将youshell.sh修改为你自己的脚本名 编写自己的脚本后保 ...

  4. zip、rar压缩文件密码破解——使用ARCHPR Professional Edition

    直链下载地址: https://pan.abn.cc/weiyun/down.php?u=82441366e3c1f43fc69210e8ece93470.undefined.zip (压缩包内含解压 ...

  5. 常用宏OC

    #ifndef MacroDefinition_h #define MacroDefinition_h //-------------------获取设备大小--------------------- ...

  6. 从.net到java,从基础架构到解决方案。

    这一年,职业生涯中的最大变化,是从.net到java的直接跨越,是从平台架构到解决方案的不断完善. 砥砺前行 初出茅庐,天下无敌.再学三年,寸步难行.很多时候不是别人太强,真的是自己太弱,却不自知. ...

  7. Codeforces Round #323 (Div. 2) D 582B Once Again...(快速幂)

    A[i][j]表示在循环节下标i开头j结尾的最长不减子序列,这个序列的长度为p,另外一个长度为q的序列对应的矩阵为B[i][j], 将两序列合并,新的序列对应矩阵C[i][j] = max(A[i][ ...

  8. ELF文件的格式和加载过程

    http://blog.csdn.net/lingfong_cool/article/details/7832896 (一) ELF 文件的格式       ELF 文件类型 (1) 可重定位文件(  ...

  9. Charles拦截请求

    一.通过Charles抓包,可拦截请求并篡改交互信息 1.可篡改客户端向服务器发起的请求信息(服务器收到的是假消息) 2.可篡改服务器返回给客户端的响应结果(客户端看到的是假消息) 二.篡改用户请求 ...

  10. Bootstrap HTML编码规范

    语法 1.用两个空格来代替制表符(Tab)--这是唯一能保证在所有的环境下获得一致展现的方法. 2.嵌套元素应当缩进一次(即两个空格). 3.对于属性的定义,属性值确保全部都用双引(避免使用单引号). ...