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. 探究js正则匹配方法:match和exec

    match是字符串方法,写法为:str.match(reg) exec是正则表达式方法,写法为:reg.exec(str) match和exec在匹配成功时返回的都是数组,在没有匹配上时返回的都是nu ...

  2. Kotlin Reference (九) Properties and Fields

    most from reference 声明属性 Koltin的类都有属性,这些属性可以声明为可变的,使用var关键字或用val关键字生声明不可变属性. class Address { var nam ...

  3. PyQt4 HardwareManager

    # PyQt4 HardwareManager # 声明: # 本软件主要是由于朋友说想要一个产品缺陷记录软件,主要用于记录产品缺陷, # 通过产品序列号进行插入.查询,本来想用VC++ 6.0做,但 ...

  4. Yii隐藏单入口

    Yii进入项目首页时默认是index.php文件路径,如何把index.php去掉,方法如下: 打开apache配置文件http.conf,找到如下的代码: #LoadModule rewrite_m ...

  5. BZOJ4977: [[Lydsy1708月赛]跳伞求生(不错的贪心)

    4977: [[Lydsy1708月赛]跳伞求生 Time Limit: 5 Sec  Memory Limit: 256 MBSubmit: 446  Solved: 142[Submit][Sta ...

  6. idea 使用spring boot 搭建freemarker模板

      一丶新建maven spring boot 项目 新建好了开始使用模板 先看一个目录结构 二丶配置pox.xml <?xml version="1.0" encoding ...

  7. DesignPattern(三)结构型模式(上)

    结构型模式 结构型模式,顾名思义讨论的是类和对象的结构 ,主要用来处理类或对象的组合.它包括两种类型,一是类结构型模式,指的是采用继承机制来组合接口或实现:二是对象结构型模式,指的是通过组合对象的方式 ...

  8. lnmp -- 解决Warning: scandir() has been disabled for security reasons in…的问题

    原因:LNMP 0.9禁用了部分存在危险的PHP函数 LNMP0.9禁用的PHP函数包括:passthru, exec, system, chroot, scandir, chgrp, chown, ...

  9. redis的maxmemory与maxmemory-policy关系

    如果redis配置了maxmemory和maxmemory-policy策略,则当redis内存数据达到maxmemory时,会根据maxmemory-policy配置来淘汰内存数据,以避免OOM.r ...

  10. php 文件上传$_FILES中error返回值详解

    用PHP上传文件时,我们会用程序去监听浏览器发送过来的文件信息,首先会通 过$_FILES[fieldName]['error']的不同数值来判断此欲上传的文件状态是否正常.$_FILES[field ...