【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 ...
随机推荐
- python namedtuple命名元组
from collections import namedtuple Animal=namedtuple('Animal','name age type') perry=Animal(name='pe ...
- Android中判断service是否在运行
/** * 判断服务是否开启 * * @return */ public static boolean isServiceRunning(Context context, String Service ...
- ISE报警:关键字 unsigned不可用于verilog
问题:关键字 unsigned不可用于verilog 解决方案:去掉unsigned
- checkbox 框 选中判断
function checkAll(checktop){ $(":checkbox[name='id']").prop("checked",checktop.c ...
- (转)Linux运维MySQL必会面试题100道
老男孩教育Linux运维班MySQL必会面试题100道 (1)基础笔试命令考察 (要求:每两个同学一组,一个口头考,一个上机实战作答,每5个题为一组,完成后换位) 1.开启MySQL服务 2.检测端口 ...
- 【随笔】使用apt-spy来更新你的debian源
debian什么最方便,当然是用apt-get intsall 命令来安装软件了.使用apt-get什么最重要,自然是下载源了. debian版本自带的源肯定不是最快的,考虑到个人所处的位置.网速等方 ...
- Node.js Mongoose数据库连接失败 提示:Authentication failed
mongoose.connect('mongodb://username:password@127.0.0.1:27017/qianxunkefu_db')换成mongoose.connect('mo ...
- 深入redis内部--初始化服务器
初始化服务器代码如下: void initServer() { int j; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); setupSigna ...
- show_space
create or replace procedure show_space( p_segname_1 in varchar2,p_space in varchar2 default 'AUTO',p ...
- linq中where与skipwhile区别
//字符串数组 string[] names = { "a1", "a2", "bcd","ab","bcde ...