Given an array S of n integers, are there elements abc, 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的更多相关文章

  1. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. 【LeetCode题意分析&解答】37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  3. 【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 ...

  4. ACM金牌选手整理的【LeetCode刷题顺序】

    算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...

  5. 【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 ...

  6. 【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 ...

  7. 【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 ...

  8. 【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 ...

  9. 【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 ...

  10. 【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 ...

随机推荐

  1. Linux工具安装配置

    1.修改主机名/添加别名访问 修改/etc/sysconfig/network中的hostnameNETWORKING=yesHOSTNAME=dlserver01; 修改/etc/hosts文件 1 ...

  2. ios 开发之旅

    你可能还在跟我一样傻傻的研究,怎么用visual studio 开发ios 里,哪就浪费时间吧!因为在安装 xmarin的时候,自动可以选择ios for Visual studio ,安装完也不能编 ...

  3. 基于CommonKADS方法论实现知识库系统

    说明:本文是Knowledge-based systems with thecommonKADS method文章的翻译. 一.知识库系统的背景 1. 什么是知识库系统(KBS) 知识库系统是人工智能 ...

  4. 关于javascript中时间格式和时间戳的转换

    当前时间获取的各种函数: var myDate = new Date();myDate.getYear();        //获取当前年份(2位),已经不推荐使用myDate.getFullYear ...

  5. spring-boot 应用配置文件(.properties或.yml)

    1.应用配置文件(.properties或.yml) .properties在配置文件中直接写: name=Isea533 server.port=8080 .yml格式的配置文件如: name: I ...

  6. html控件

    checkbox val = "<li class='layer'><label><input type='checkbox' checked name='la ...

  7. React.js 小书 Lesson25 - 实战分析:评论功能(四)

    作者:胡子大哈 原文链接:http://huziketang.com/books/react/lesson25 转载请注明出处,保留原文链接和作者信息. (本文未审核) 目前为止,第二阶段知识已经基本 ...

  8. cut、grep和排序命令

    1.cut 对于行进行操作 cut -d ':' -f 2 以':'为分隔符,切出第二部分的所有行 cut -c 12- 从第12字符往后的字符所有行 2.grep grep '选取的串' 选出所有含 ...

  9. Shell脚本之awk详解

    一.基本介绍 1.awk: awk是一个强大的文本分析工具,在对文本文件的处理以及生成报表,awk是无可替代的.awk认为文本文件都是结构化的,它将每一个输入行定义为一个记录,行中的每个字符串定义为一 ...

  10. [转]oracle中查看用户权限

    本文转自:http://www.cnblogs.com/QDuck/archive/2010/08/11/1797225.html 1.查看所有用户:   select * from dba_user ...