LeetCode_3Sum
一.题目
3Sum
Total Accepted: 45112 Total
Submissions: 267165My
Submissions
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)
二.解题技巧
要保证不出现反复的情况,当i!=0时,假设第i个数与第i-1个数同样的话,则不进行处理,直接处理第i+1个元素。这样。仅仅要保证三个数中最小的数是依照顺序递增的。那么算法找到的解就都是不反复的。
三.实现代码
class Solution
{
public:
vector<vector<int> > threeSum(vector<int> &num)
{
int Size = num.size(); vector<vector<int> > Result; if (Size < 3)
{
return Result;
} sort(num.begin(), num.end()); for (int Index_outter = 0; Index_outter < (Size - 2); Index_outter++)
{
int First = num[Index_outter];
int Second = num[Index_outter + 1];
const int Target = 0; if ((Index_outter != 0) && (First == num[Index_outter - 1]))
{
continue;
} int Start = Index_outter + 1;
int End = Size - 1; while (Start < End)
{
Second = num[Start];
int Third = num[End]; int Sum = First + Second + Third; if (Sum == Target)
{
vector<int> Tmp;
Tmp.push_back(First);
Tmp.push_back(Second);
Tmp.push_back(Third); Result.push_back(Tmp); Start++;
End--;
while (num[Start] == num[Start - 1])
{
Start++;
}
while (num[End] == num[End + 1])
{
End--;
} } if (Sum < Target)
{
Start++;
while (num[Start] == num[Start -1])
{
Start++;
}
} if (Sum > Target)
{
End--;
if (num[End] == num[End + 1])
{
End--;
}
} } }
return Result; }
};
四.体会
版权全部,欢迎转载,转载请注明出处。谢谢

LeetCode_3Sum的更多相关文章
- LeetCode_3Sum Closest
一.题目 3Sum Closest Total Accepted: 32191 Total Submissions: 119262My Submissions Given an array S of ...
随机推荐
- ES6(Module模块化)
模块化 ES6的模块化的基本规则或特点: 1:每一个模块只加载一次, 每一个JS只执行一次, 如果下次再去加载同目录下同文件,直接从内存中读取. 一个模块就是一个单例,或者说就是一个对象: 2:每一个 ...
- H5系列之History(必知必会)
H5系列之History(必知必会) 目录 概念 兼容性 属性 方法 H5方法 概念 理解History Api的使用方式 目的是为了解决哪些问题 作用:ajax获取数据时 ...
- ctype.h 第2章
ctype.h ctype.h是c标准函数库中的头文件 定义了一批c语言字符分类函数 (c character classification functions) 用于测试字符是否属于特定的字 ...
- 【java基础 11】java集合框架学习
导读:本篇博客主要是从整体上了解java的集合框架,然后主要介绍几个自己在项目中用到的结构,比如说:hashtable.hashmap.hashset.arraylist等! 一.宏观预览 从宏观上看 ...
- poj2104&&poj2761 (主席树&&划分树)主席树静态区间第k大模板
K-th Number Time Limit: 20000MS Memory Limit: 65536K Total Submissions: 43315 Accepted: 14296 Ca ...
- shell的if-else的基本用法
if 语句通过关系运算符判断表达式的真假来决定执行哪个分支.Shell 有三种 if ... else 语句: if ... fi 语句: if ... else ... fi 语句: if ... ...
- jquery滚动条插件slimScroll
参数 width: 'auto', //可滚动区域宽度 height: '100%', //可滚动区域高度 size: '10px', //组件宽度 c ...
- 【Luogu】P2331最大子矩阵(DP)
题目链接 这题的状态转移方程真是粗鄙. f[i][j][k]表示前i行用了j个矩阵状态为k的时候的最大值. k=0:两列都不选. k=1:取左弃右. k=2:选右弃左. k=3:左右都选,但分属于两个 ...
- ACM程序设计选修课——1081: 堆(BFS)
1081: 堆 Time Limit: 1 Sec Memory Limit: 128 MB Submit: 26 Solved: 9 Description Input Output Sampl ...
- [ZJOI2007]时态同步 (树形DP)
题目描述 小 Q在电子工艺实习课上学习焊接电路板.一块电路板由若干个元件组成,我们不妨称之为节点,并将其用数字 1,2,3-.进行标号.电路板的各个节点由若干不相交的导线相连接,且对于电路板的任何两个 ...