【3Sum】cpp
题目:
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)
代码:
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的更多相关文章
- 【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 = ...
- 【Permutations】cpp
题目: Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the fo ...
- 【Subsets】cpp
题目: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset ...
- 【Anagrams】 cpp
题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...
- 蓝桥杯 【dp?】.cpp
题意: 给出一个2*n的方格,当刷完某一个方格的漆后可以且只可以走到相邻的任何一格,即上 下 左 右 左上 左下 右上 右下.可以从任意一个格子开始刷墙,问有多少种刷法,因为随着n的增大方案数会变多, ...
- 【Triangle 】cpp
题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...
- 【N-Queens】cpp
题目: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two que ...
- 【Combinations】cpp
题目: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For ex ...
- 【Candy】cpp
题目: There are N children standing in a line. Each child is assigned a rating value. You are giving c ...
随机推荐
- MATLAB之数据处理+公式拟合
MATLAB之数据处理+公式拟合 前言:由试验得到一组数据,对该组数据进行处理,作图分析,分析各变量的关系,期望得到拟合公式. 试验数据背景 本次试验有三个自变量:V.M.G,因变量为F,每组试验重复 ...
- meterpreter > ps
meterpreter > ps Process List============ PID PPID Name Arch Session User Path --- ---- ---- ---- ...
- 新增自定义聚合函数StrJoin
1.添加程序集Microsoft.SqlServer.Types CREATE ASSEMBLY [Microsoft.SqlServer.Types] AUTHORIZATION [sys] FRO ...
- SSH中懒加载异常--could not initialize proxy - no Session
SSH进行关联的表进行显示时出现的问题,老是显示你的OGNL表达式错误,但是找了很久确实没错,在网上找了一下,下面的这个方法本人认为是最有效的方法(已经测试可以使用) 在web.xml中加入 程序代码 ...
- IOS PickerView使用
- (void)viewDidLoad { [super viewDidLoad]; // 1.创建pickerview // pickerview有默认的frame UIPickerView *pi ...
- POJ 3734 Blocks (线性递推)
定义ai表示红色和绿色方块中方块数为偶数的颜色有i个,i = 0,1,2. aij表示刷到第j个方块时的方案数,这是一个线性递推关系. 可以构造递推矩阵A,用矩阵快速幂求解. /*********** ...
- POJ-1149 PIGS---最大流+建图
题目链接: https://vjudge.net/problem/POJ-1149 题目大意: M个猪圈,N个顾客,每个顾客有一些的猪圈的钥匙,只能购买这些有钥匙的猪圈里的猪,而且要买一定数量的猪,每 ...
- sqlldr将txt导入oracle数据库
注意事项: 1.userid 和 control关键字不要缺少: 2.注意数据库格式:test/test@数据库IP:1521/Oracle8,最后一个是tnsnames中的service_name, ...
- Java代码工具箱之链接Oracle
1. 需要oracle的 odbc jar包 2. 代码 3. 注意:ps对象和statement对象最好用完立即释放,尤其是读写数据库代码出现在 for 循环语句中时. 否则会出现游标不够的情况, ...
- 课堂使用的Linux命令
1.ls 显示目录文件 2.ls -l = ll 显示 3.vi 创建于编辑 4.mv 改名 5. ./ 当前目录 6.chmod 修改权限 4 读 2 编辑 1 运行 7.去除UI界面 syste ...