6.3Sum && 4Sum [ && K sum ] && 3Sum Closest
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)
解析:分三步: a.排序. b. 任取一个没取过的数,余下右边的序列中求 2Sum. c. 取2Sum的过程中,应保证没有重复。
// O(n^2 + nlogn) // no set used!
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > vec;
vector<int> vec2(3, 0);
int n = num.size();
if(n < 3) return vec;
sort(num.begin(), num.end());
/* promise not occur again */
int preValue = num[0] + 1;
for(int i = 0; i < n-2; ++i){
if(num[i] == preValue) continue;
else preValue = num[i];
/* 2Sum */
int j = i + 1, k = n-1;
while(j < k ){
int sum = num[j] + num[k] + num[i];
if(sum== 0){
vec2[0] = num[i]; vec2[1] = num[j]; vec2[2] = num[k];
while(j < k && num[j] == num[j+1]) ++j; // promise not occur again
while(j < k && num[k] == num[k-1]) --k;
vec.push_back(vec2);
++j,--k;
}else if(sum < 0){
++j;
} else --k;
}
}
return vec;
}
};
4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
解析:3Sum 之上加一层循环。
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > vec;
vector<int> ans(, ); // record one answer
int n = num.size();
if(n < ) return vec;
sort(num.begin(), num.end());
int preVal4 = num[] ^ 0x1;
for(int i = ; i < n - ; ++i){
if(num[i] == preVal4) continue;
else preVal4 = num[i];
int preVal3 = num[i+] ^ 0x1;
for(int j = i+; j < n - ; ++j){
if(num[j] == preVal3) continue;
else preVal3 = num[j];
int s = j + , t = n - , target2 = target - num[i] - num[j];
while(s < t){
int sum = num[s] + num[t];
if(sum == target2){
ans[] = num[i]; ans[] = num[j]; ans[] = num[s]; ans[] = num[t];
while(s < t && num[s] == num[s+]) ++s;
while(s < t && num[t] == num[t-]) --t;
vec.push_back(ans);
++s, --t;
}else if(sum < target2) {
++s;
}else --t;
}
}
}
return vec;
}
};
Code
kSum(刷题模版)
class Solution {
public:
vector<vector<int> > kSum(vector<int> &num,int k, int target) {
vector<vector<int> > vec;
vector<int> vec2;
if(num.size() < k) return vec;
sort(num.begin(), num.end());
getSum(vec, vec2, num, 0, k, target);
return vec;
} void getSum(vector<vector<int> > &vec, vector<int> &vec2, vector<int> &num, int begin, int k, int target){
if(k == 2){
int len = num.size(), s = begin, t = len - 1;
while(s < t){
int sum = num[s] + num[t];
if(sum == target){
vec2.push_back(num[s]); vec2.push_back(num[t]);
while(s < t && num[s] == num[s+1]) ++s;
while(s < t && num[t] == num[t-1]) --t;
vec.push_back(vec2);
vec2.pop_back(); vec2.pop_back(); // key
++s, --t;
}else if(sum < target) {
++s;
}else --t;
} }else {
int len = num.size();
int preValue = num[begin] ^ 0x1;
for(int start = begin; start < len-k+1; ++start){
if(num[start] == preValue) continue;
else preValue = num[start];
vec2.push_back(num[start]);
getSum(vec, vec2, num, start + 1, k - 1, target - num[start]);
vec2.pop_back();
}
}
}
};
算法复杂度分析:
k-SUM can be solved more quickly as follows.
For even k: Compute a sorted list S of all sums of k/2 input elements. Check whether S contains both some number x and its negation −x. The algorithm runs in O(nk/2logn) time.
For odd k: Compute the sorted list S of all sums of (k−1)/2 input elements. For each input element a, check whether S contains both x and a−x, for some number x. (The second step is essentially the O(n2)-time algorithm for 3SUM.) The algorithm runs in O(n(k+1)/2) time.
Both algorithms are optimal (except possibly for the log factor when k is even and bigger than 2) for any constant k in a certain weak but natural restriction of the linear decision tree model of computation.
3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int len = num.size();
if(len < 3){
printf("Number of elements is less than 3.\n");
return 0;
}
sort(num.begin(), num.end());
int minDiff = 0x7fffffff; // note: a = 0x80000000; abs(a) == -2147483648;
int preValue3 = num[0] + 1; // jump the number appeared again.
for(int i = 0; i < len - 2; ++i){
if(num[i] == preValue3) continue;
else preValue3 = num[i]; int s = i + 1, t = len - 1, temVal = num[i] - target;
while(s < t){
int curDiff = temVal + num[s] + num[t];
if(curDiff == 0) return target;
else if(curDiff < 0) ++s;
else --t; if(abs(curDiff) < abs(minDiff)) minDiff = curDiff;
}
}
return target + minDiff;
}
};
6.3Sum && 4Sum [ && K sum ] && 3Sum Closest的更多相关文章
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
前言: 这几天在做LeetCode 里面有2sum, 3sum(closest), 4sum等问题, 这类问题是典型的递归思路解题.该这类问题的关键在于,在进行求和求解前,要先排序Arrays.sor ...
- LeetCode Two Sum&Two Sum II - Input array is sorted&3Sum&4Sum 一锅煮题解
文章目录 Two Sum Two Sum II 3Sum 4Sum Two Sum 题意 给定一个数组,和指定一个目标和.从数组中选择两个数满足和为目标和.保证有且只有一个解.每个元素只可以用一次. ...
- k sum 问题系列
转自:http://tech-wonderland.net/blog/summary-of-ksum-problems.html (中文旧版)前言: 做过leetcode的人都知道, 里面有2sum, ...
- LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum
1. Two Sum 题目链接 题目要求: Given an array of integers, find two numbers such that they add up to a specif ...
- K Sum(2 Sum,3 Sum,4 Sum,3-Sum Closest)
算是经典算法问题了.这里主要针对只存在一个解或者只需要求一个解的情况描述一下解题思路.若需要找到所有可能解,方法需要略作调整.如有问题,欢迎指正. 2 sum: 如果已排序,可直接用夹逼法,即两指针从 ...
- 2Sum,3Sum,4Sum,kSum,3Sum Closest系列
1).2sum 1.题意:找出数组中和为target的所有数对 2.思路:排序数组,然后用两个指针i.j,一前一后,计算两个指针所指内容的和与target的关系,如果小于target,i右移,如果大于 ...
- summary of k Sum problem and solutions in leetcode
I found summary of k Sum problem and solutions in leetcode on the Internet. http://www.sigmainfy.com ...
- lintcode: k Sum 解题报告
K SUM My Submissions http://www.lintcode.com/en/problem/k-sum/ 题目来自九章算法 13% Accepted Given n distinc ...
随机推荐
- [转]HttpURLConnection的使用
/* * URL请求的类别分为二类,GET与POST请求.二者的区别在于: * a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet, * b:) post与get ...
- linux下用命令导出mysql表数据
由于数据库服务器是内网环境,只能通过linux跳板机连接,所以navicat工具暂时用不上. 1.用Xshell工具连接跳板机 2.再通过跳板机连接数据库服务器 >ssh -p port ip ...
- sql 跨域
1. 开通分布式查询权限 reconfigure reconfigure 2. 查询 ',NETACS.dbo.tb_car) a select * from opendatasource('SQLO ...
- 2014年5月份第2周51Aspx源码发布详情
Reapter手写分页控件源码 2014-5-12 [VS2010]源码描述:实现repeater控件分页,方便好用,界面设计也很漂亮.数据库是Access,可直接运行.入口是RepeaterTes ...
- 2016 - 1 - 23 json解析
一: json 1. 什么是json 1.1 json是一种轻量级的数据格式,一般用于数据交互. 1.2 服务器返回给客户端的数据,一般都是JSON或者XML格式(文件下载除外). 2. JS ...
- 三部曲一(数据结构)-1024-Eqs
解方程整数解的题,通过这道题我学会了这种题的一般做法,对于未知数较少.取值范围较小且解为整数的方程,把一半的未知数移到等式的另一边,然后对两边分别枚举,用哈希配对,如果有相同的结果就找到一组解.具体做 ...
- 使用POSIX正则库匹配一行中多个结果
正则匹配与正则表达式是什么东西我就不说了,在这里说下POSIX这个c语言正则库在对字符串进行正则匹配时取出多个结果的问题. 首先简单说明下POSIX正则库的几个函数和使用方法 第一个函数:int re ...
- Apache Jena - A Bootstrap
前言 这篇文档属探究立项性质,作为语义网和本体建模工作的延续. 依照NoSQL Distilled上的考察方法,将Apache Jena作为图数据库的泛型考察. 内容 多种出版物上声明主要有四类N ...
- JAVA修饰符类型(public,protected,private,friendly)
转自:http://www.cnblogs.com/webapplee/p/3771708.html JAVA修饰符类型(public,protected,private,friendly) publ ...
- 有关使用seajs和template模板的总结
方法一:使用<script type="text/javascript" src="../js/lib/template.js"></scri ...