【Leetcode】【Medium】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)
- 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)
解题思路o(n2):
先对数组进行排序,排序后以每一个数组元素为目标值,在其他的元素中寻找余下的两个元素,使这三个元素之和为0;那么此题就转化为leetcode中另一道TwoSum的问题,由于3Sum已经提前排序,因此TwoSum中的hash表技巧在这种思路下就没有时间复杂度优势了。
注意:
1、不需要遍历所有数组元素,只需要将所有非正元素,或者所有非负元素依次作为目标值即可;
2、在相同目标值的前提下,TwoSum可能有多种匹配对(当然);
3、此题最重要的是避免返回的答案序列出现重复,重复有两种情况:
(1)TwoSum的计算结果出现重复。
解决方法:以i和j从序列两头向中间遍历,如果遇到符合条件的i和j,则跨越所有值相同的i和j,再继续遍历之后的数字;
(2)目标值出现重复。
解决方法:a. 从左向右遍历,只遍历非正数;(或者从右向左遍历,只遍历非负数)
b. 跨过所有相同的重复数字;
重复去除的关键在于,第一次出现重复数字时,其数字选择完全包含了之后重复数字的选择,那么之后遇到重复数字直接略过就行了。
解题步骤:
1、复制输入数组,并对复制数组进行排序;
2、新建一个保存结果的二维数组;
3、从0开始遍历,直到复制数组元素<=0:
(1)将遍历到的元素下标,随同复制数组以及保存结果的二维数组,传入FindTwoSum函数中。
(2)略过和遍历到的元素相同的元素;
4、返回结果数组;
对于FindTwoSum:
1、从遍历元素下标+1,到数组末尾,两端向中间遍历此数组:
(1)判断两端及遍历元素,三者之和是否为0;进而做++i和++j的处理;
(2)三者和为0,则这三者放入结果数组中,并且略过重读的num[++i]和num[--j];
AC代码:
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(), num.end());
int size = num.size();
vector<vector<int> > result;
for (int i = ; i < size - && num[i] <= ; ++i) {
FindTwoSum(result, num, i);
while (num[i] == num[i+])
++i;
}
return result;
}
void FindTwoSum(vector<vector<int> > &result, vector<int> num, int target_idx) {
int target = num[target_idx];
int i = target_idx + ;
int j = num.size() - ;
while (i < j) {
if (num[i] + num[j] + target > ) {
--j;
} else if (num[i] + num[j] + target < ) {
++i;
} else {
vector<int> oneMatch {target, num[i], num[j]};
result.push_back(oneMatch);
while (num[i] == num[++i]);
while (num[j] == num[--j]);
}
}
return;
}
};
【Leetcode】【Medium】3Sum的更多相关文章
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【LeetCode题意分析&解答】37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...
- 【LeetCode题意分析&解答】35. Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the ...
- ACM金牌选手整理的【LeetCode刷题顺序】
算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...
- 【LeetCode算法题库】Day5:Roman to Integer & Longest Common Prefix & 3Sum
[Q13] Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Valu ...
- 【leetcode刷题笔记】3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- 【leetcode刷题笔记】3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...
- 【LeetCode从零单排】No15 3Sum
称号 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all ...
- 【LeetCode每天一题】3Sum Closest(最接近的三数和)
Given an array nums of n integers and an integer target, find three integers in nums such that the s ...
- 【LeetCode每天一题】3Sum(三数之和)
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find ...
随机推荐
- 接口自动化测试框架 :APIAutoTest框架
前言 随着测试技术的发展,接口自动化测试逐渐成为各大公司投入产出比最高的测试技术.介入时间早,执行效率高,稳定性高的优点,让越来越多的公司引入接口自动化测试. 框架简介 APIAutoTest是处理A ...
- Python - 购物车代码 (账户登陆,用户个人清单存取,重要信息高亮显示)
需要掌握open函数. 清单存取时,需要注意编码问题,直接在读取和存储时加上encoding = 'utf - 8' 可以解决gbk - unicode转化时出现的乱码问题. 码农一定要坚强,这份代码 ...
- SQL语句模糊查询年月
<if test="uploadTime != null" > <![CDATA[ and date_format(w.upload_time, '%Y%m') ...
- LoadRunner使用
LoadRunner使用 软件版本:12.53 build 1203 操作系统: Windows7 以下内容摘录自LoadRunner的官方帮助文档. 介绍 LoadRunner现在是HP公司的产品, ...
- 【百度之星2014~复赛 解题报告~正解】The Query on the Tree
声明 笔者最近意外的发现 笔者的个人网站http://tiankonguse.com/ 的很多文章被其它网站转载,但是转载时未声明文章来源或参考自 http://tiankonguse.com/ 网站 ...
- Error opening zip file or JAR manifest missing的解决方法
错误描述: MyEclipse中启动Tomcat(debug)的时候就出现Error starting Tomcat : A configuration error occured during st ...
- CentOS7配置中文
CentOS7配置中文 yum install kde-l10n-Chinese -y vim /etc/locale.conf修改为zh_CN.UTF-8 vim /etc/environment添 ...
- redis操作基本命令
Redis—— Remote Dictionary Server,它是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API,我们 ...
- 阿里Java开发电话面试经历--惨败
近期准备跳槽,想试试知名大企业--阿里.经过boss直聘上一些内部人员的内推,有幸获得了一次电话面试的机会.(虽然在面试开始之前就大概知道结果是如何,但是也总得试试自己个有多水,哈哈哈...) 跟大家 ...
- php strpos返回字符串首次出现的位置
(PHP 4, PHP 5, PHP 7) strpos — 查找字符串首次出现的位置 说明 mixed strpos ( string $haystack , mixed $needle [, in ...