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)

思路I: 用求3Sum的方法,外加一次for循环,时间复杂度O(n3)

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int size = nums.size();
if(size < ) return result; sort(nums.begin(), nums.end());
for(int i = ; i < size-; i++){
if(i > && nums[i]==nums[i-]) continue; //The solution set must not contain duplicate=>no duplicate in the same position
for(int j = i+; j < size-; j++){
if(j> i+ && nums[j]==nums[j-]) continue; //The solution set must not contain duplicate=>no duplicate in the same position
find(nums, j+, size-, target-nums[i]-nums[j], i, j);
}
}
return result;
}
void find(vector<int>& nums, int start, int end, int target, int& index1, int& index2){
int sum;
while(start<end){
sum = nums[start]+nums[end];
if(sum == target){
item.clear();
item.push_back(nums[index1]);
item.push_back(nums[index2]);
item.push_back(nums[start]);
item.push_back(nums[end]);
result.push_back(item);
do{ //The solution set must not contain duplicate=>no duplicate in the same position
start++;
}while(start!= end && nums[start] == nums[start-]);
do{ //The solution set must not contain duplicate=>no duplicate in the same position
end--;
}while(end!=start && nums[end] == nums[end+]);
}
else if(sum>target){
do{ //The solution set must not contain duplicate=>no duplicate in the same position
end--;
}while(end!=start && nums[end] == nums[end+]);
}
else{//The solution set must not contain duplicate=>no duplicate in the same position
do{
start++;
}while(start!= end && nums[start] == nums[start-]);
}
}
} private:
vector<vector<int>> result;
vector<int> item;
};

思路II:用hash table。O(N^2)把所有pair存入hash表,pair中两个元素的和就是hash值。那么接下来求4sum就变成了在所有的pair value中求 2sum,这个就成了线性算法了。所以整体上这个算法是O(N^2)+O(n) = O(N^2)。

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int size = nums.size();
int a, b, c, d;
vector<vector<int>> result;
unordered_map<int,vector<pair<int,int> > > mp;
unordered_map<int,int> cnt; //各个数的数量
if(size < ) return result; sort(nums.begin(), nums.end());
for(int i = ; i < size-; i++){
if(i > && nums[i]==nums[i-]) continue;
for(int j = i+; j < size; j++){
if(j> i+ && nums[j]==nums[j-]) continue;
mp[nums[i]+nums[j]].push_back(pair<int,int>{nums[i],nums[j]});
}
} for(int i = ; i < size; i++){
cnt[nums[i]]++;
} for(unordered_map<int,vector<pair<int,int> > >::iterator it1=mp.begin();it1!=mp.end();it1++){//遍历map
unordered_map<int,vector<pair<int,int> > >::iterator it2=mp.find(target - it1->first); //查找map
if(it2==mp.end()) continue;// not found
if(it1->first > it2->first) continue; //already checked,去重 for(int i = ; i < it1->second.size(); i++){//访问map元素
for(int j = ; j < it2->second.size(); j++){
a = it1->second[i].first; //访问pair元素
b = it1->second[i].second;
c = it2->second[j].first;
d = it2->second[j].second; if(max(a,b) > min(c,d)) continue; //四个数两两组合,有6种情况,这里只取两个最小的数在it1的情况,去重
cnt[a]--;
cnt[b]--;
cnt[c]--;
cnt[d]--;
if(cnt[a]<||cnt[b]<||cnt[c]<||cnt[d]<){
cnt[a]++;
cnt[b]++;
cnt[c]++;
cnt[d]++;
continue;
} cnt[a]++;
cnt[b]++;
cnt[c]++;
cnt[d]++;
vector<int> tmp = {a,b,c,d};
sort(tmp.begin(),tmp.end());
result.push_back(tmp);
}
}
}
return result;
}
};

18.4Sum (Map)的更多相关文章

  1. [LeetCode][Python]18: 4Sum

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 18: 4Sumhttps://oj.leetcode.com/problem ...

  2. LeetCode 15. 3Sum 16. 3Sum Closest 18. 4Sum

    n数求和,固定n-2个数,最后两个数在连续区间内一左一右根据当前求和与目标值比较移动,如果sum<target,移动较小数,否则,移动较大数 重复数处理: 使i为左至右第一个不重复数:while ...

  3. 1. Two Sum&&15. 3Sum&&18. 4Sum

    题目: 1. Two Sum Given an array of integers, return indices of the two numbers such that they add up t ...

  4. leetcode 1.Two Sum 、167. Two Sum II - Input array is sorted 、15. 3Sum 、16. 3Sum Closest 、 18. 4Sum 、653. Two Sum IV - Input is a BST

    1.two sum 用hash来存储数值和对应的位置索引,通过target-当前值来获得需要的值,然后再hash中寻找 错误代码1: Input:[3,2,4]6Output:[0,0]Expecte ...

  5. 15. 3Sum、16. 3Sum Closest和18. 4Sum

    15 3sum Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = ...

  6. 18. 4Sum (JAVA)

    Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums s ...

  7. 1. Two Sum + 15. 3 Sum + 16. 3 Sum Closest + 18. 4Sum + 167. Two Sum II - Input array is sorted + 454. 4Sum II + 653. Two Sum IV - Input is a BST

    ▶ 问题:给定一个数组 nums 及一个目标值 target,求数组中是否存在 n 项的和恰好等于目标值 ▶ 第 1题,n = 2,要求返回解 ● 代码,160 ms,穷举法,时间复杂度 O(n2), ...

  8. 【LeetCode】18. 4Sum (2 solutions)

    4Sum Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d  ...

  9. [LeetCode] 18. 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 ...

随机推荐

  1. Hibernate查询视图返回null问题说明及解决办法

    在Hibernate中对含有主键的单表操作比较简单,直接使用Hibernate针对数据库表对象进行反向生成代码,直接调用就可以了.但是在实际项目当中,经常会用到不少的多表联合查询操作,网上有很多示例, ...

  2. jinja 2 filter 使用

    文档地址 http://jinja.pocoo.org/docs/templates/#builtin-filters indent indent(s, width=4, indentfirst=Fa ...

  3. kvm虚拟机添加网卡

    前几篇文章介绍了有关KVM安装虚拟机以及如何给虚拟机添加硬盘,今天我们再来介绍下有关如何给KVM虚拟机添加网卡. 给KVM虚拟机添加网卡,可以分为两种形式:图形界面的和virsh attach-int ...

  4. linux find查找并拷贝 exec xargs区别

    -exec    1.参数是一个一个传递的,传递一个参数执行一次rm    2.文件名有空格等特殊字符也能处理-xargs     1.一次将参数传给命令,可以使用-n控制参数个数    2.处理特殊 ...

  5. leetcode122 买卖股票的最佳时机 python

    题目:给定一个数组,它表示了一只股票的价格浮动,第i个元素代表的是股票第i天的价格.设计一个函数,计算出该股票的最大收益,注意,可以多次买入卖出,但下一次买入必须是在本次持有股票卖出之后.比如[1,7 ...

  6. Android 开发有哪些新技术出现?

    这里记录一下在知乎回答的<Android 开发有哪些新技术出现?>.知乎链接在这里. 原问题如下: Android 开发有哪些新技术出现?可以从UI设计或者一些核心的算法之类的说起 这是我 ...

  7. webdriver的2种等待

    隐性等待是指当要查找元素,而这个元素没有马上出现时,告诉WebDriver查询Dom一定时间,默认值是0,但是设置之后,这个时间将在WebDriver对象实例整个生命周期都起作用 driver.man ...

  8. 【转】Linux下的文本dos格式转Unix格式,去除^M符号

    原文网址:http://blog.csdn.net/kobejayandy/article/details/13291525 问:我在Windows中通过FTP传一个文本文件到Linux中,但是打开文 ...

  9. PhpStorm 10.0.3 下载安装与汉化

    https://www.7down.com/soft/229568.html 2JA97R55MG-eyJsaWNlbnNlSWQiOiIySkE5N1I1NU1HIiwibGljZW5zZWVOYW ...

  10. Erlang tool -- recon

    遇见recon 以来, 每次定位系统瓶颈, 总是能让我眼前一亮. 比如说, 定位非尾递归导致的内存暴涨, 定位引发CPU满载的进程.得心应手,每每额手称庆. recon 是ferd 大神 释出的一个 ...