【Leetcode】【Medium】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)
在Leetcode中,除了4Sum以外,还有3Sum以及2Sum,有兴趣的朋友可以点击链接参考。
一、解题思路1:
在3Sum以及2Sum的基础上,可以总结出KSum的通用算法,那就是数组中按序挑选数字作为target(o(n)),对于余下的序列使用(K-1)Sum算法,其中2Sum的复杂度是o(n);
二、针对4Sum的解题思路2:
1、4Sum可以分解为2Sum+2Sum;因此将原始数组中,所有数字两两求和,记录在hash表;那么原来的4Sum=target的问题,就转为从hash表中找到2个Item使其Sum之和为target的问题;满足一个值的item可能有多种组合存在(如题目中的例子item=0,那么(-1,1)(-2,2)(0,0)都应保存在此item下),因此hash表可以将键值作为item值,而将value设为一个list,保存所有满足的组合。
2、如何操作hash表:
我们可以倒过来思考,假设A+B+C+D=target,ABCD各不相同;由于hash表保存了所有元素两两之和的结果,即AB、AC、AD、BC、BD、CD都单独存在表中,如果仅仅寻找和为target的item组合的话,一共有AB+CD、AC+BD、AD+BC、BC+AD、BD+AC、CD+AB 6种情况满足和为target,但是他们都只对应一种返回值(A、B、C、D);
为了避免出现6次重复结果,由于一个item中(例AC、BD)两个元素的排列顺序也是按照从小到大有序排列,因此我们只针对AB+CD的情况筛选。即如果两个item的和等与target,同时要满足item1的第二个值B要小于item2的第一个元素C,那么可以当做结果录入返回队列中,否则当做不符合要求。
3、除了以上措施避免重复之外,由于数组队列中存在重复的元素,并且第一轮建立hash表时不会对重复元素筛选剔除。因此要注意不要将某一值计算两次;
时间复杂度:
第一部分建立hash表需要n(n-1)/2,假设两两和值有x个,每个值平均有k种组合,那么x*k = n(n-1)/2;
所以程序时间复杂度为 o( n(n-1)/2 + x*k*k ) = o( n(n-1)/2 * (1+k) ),即时间复杂度约为o(kn2) ,k取值: 1~n(n-1)/2;
最好的情况是两两和值没有重复,x=n(n-1)/2,k=1;那么程序时间复杂度为o(n2);
最坏的情况是数组中所有元素都相等,那么x=1,k=n(n-1)/2,时间复杂度接近o(n4);
AC代码:
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > ret;
unordered_map<int, vector<pair<int, int> > > hmap;
sort(num.begin(), num.end());
int size = num.size();
for (int i = ; i < size - ; ++i) {
for (int j = i + ; j < size; ++j) {
hmap[num[i]+num[j]].push_back(make_pair(i, j));
}
}
unordered_map<int, vector<pair<int, int> > >::iterator itr;
for (itr = hmap.begin(); itr != hmap.end(); ++itr) {
int new_target = target - itr->first;
if (hmap.find(new_target) == hmap.end())
continue;
vector<pair<int, int> > group1 = itr->second;
vector<pair<int, int> > group2 = hmap[new_target];
for (int i = group1.size() - ; i >= ; --i) {
if (i == group1.size() - || num[group1[i].first] != num[group1[i+].first]) {
for (int j = ; j < group2.size(); ++j) {
if (group2[j].second < group1[i].first &&
(j == || num[group2[j].first] != num[group2[j-].first])) {
vector<int> one_res {num[group2[j].first],
num[group2[j].second],
num[group1[i].first],
num[group1[i].second]};
ret.push_back(one_res);
}
}
}
}
}
return ret;
}
};
附录:
C++ Hash表操作;
【Leetcode】【Medium】4Sum的更多相关文章
- 【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刷题笔记】4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...
- 【LeetCode每天一题】4Sum(4数之和)
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums s ...
- 【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists
[Q19] Given a linked list, remove the n-th node from the end of list and return its head. Example: G ...
- 【LeetCode算法题库】Day4:Regular Expression Matching & Container With Most Water & Integer to Roman
[Q10] Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...
- 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number
[Q7] 把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...
- 【LeetCode算法题库】Day1:TwoSums & Add Two Numbers & Longest Substring Without Repeating Characters
[Q1] Given an array of integers, return indices of the two numbers such that they add up to a specif ...
随机推荐
- jsp、Servlet的面试题
3. 谈谈Servlet的生命周期 当接收到请求的时候,容器察看对应的Servlet对象是否存在,如果不存在,需要加载Servetl,实例化Servlet,调用init方法进行初始化.如果已经存在,根 ...
- 自学springboot
参考资料 https://www.renren.io/guide/
- javascrpit sort()数组对象中排序
/*ionic 调用 * @param attr 排序的属性 如number属性 * @param rev true表示升序排列,false降序排序 * */ commonSortMethod(att ...
- python学习-基础知识-1
1.计算机历史 计算机使用高低电压的两种状态来描述信息.计算机可以理解的只有二进制数据即010100011....,1个比特位可以表示的状态只有2种,n个比特位可以表示的状态有2的n次方种. 所以如果 ...
- (转)Python random模块
原文:https://my.oschina.net/cuffica/blog/33336 https://www.cnblogs.com/renpingsheng/p/7105296.html ran ...
- Django去操作已经存在的数据库
你有没有遇到过这种情况? 数据库,各种表结构已经创建好了,甚至连数据都有了,此时,我要用Django管理这个数据库,ORM映射怎么办??? Django是最适合所谓的green-field开发,即从头 ...
- Web测试注意事项
参考文章:http://www.51testing.com/html/07/n-3723307.html 总结下遇到的web测试的时候需要注意的地方: 页面分辨率: 通常是计算机的默认分辨率,但是还 ...
- KOA 与 CO 实现浅析
KOA 与 CO 的实现都非常的短小精悍,只需要花费很短的时间就可以将源代码通读一遍.以下是一些浅要的分析. 如何用 node 实现一个 web 服务器 既然 KOA 实现了 web 服务器,那我们就 ...
- 自定义ajax,添加loading效果
自定义ajax /** * @desc 自定义ajax请求,添加等待gif */ var n=0; $.defineAjax=function(obj){ n++; if(!$('#loadingDi ...
- Netbeans8的中文乱码
Netbeans8的中文乱码 前提: 不是编码的问题,统一改成UTF-8,之后文字还是显示方块.使用以下方式解决: 菜单 -> 工具 -> 选项 -> 字体和颜色 -> 语法 ...