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. New Concept English Two 3

    $课文5 无错号之虞 47. Mr.James Scott has a garage in Silbury and now he has just bought another garage in P ...

  2. bacnet ip转MQTT

    迈思德网关最新支持BACNET IP协议,可以将BACNET IP转换为MODBUS.MQTT.OPC等协议,与百度天工,阿里云等无缝对接. 支持AI.AO.DI.DO.AV.DV六个对象的读写.

  3. mysql sql语句高级写法

    将user表的内容,插入到team_member表INSERT INTO team_member (Nike,HeadImageUrl) SELECT Nike,HeadImageUrl FROM u ...

  4. [QT][SQLITE]学习记录二 日期查询

    资料例程: 1.dongfangyu SQL时间段查询 : http://blog.csdn.net/dongfangyu/article/details/4607236 2.痕网 - henw  S ...

  5. POJ 1611:The Suspects(并查集)

    The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 48327   Accepted: 23122 De ...

  6. graphql-yoga 项目简单使用&&集成docker

      graphql-yoga 是一个实现了grahql的框架,使用简单,便捷 具体源码参考github https://github.com/rongfengliang/graphql-yoga-do ...

  7. ballerina 学习十九 安全编程

      ballerina 内部提供了几种常用的安全开发模型,token 认证(jwt) basic auth jwt 安全 参考代码 import ballerina/http; http:AuthPr ...

  8. StringUtils.isEmpty()和isBlank()的区别

    一.概述 两种判断字符串是否为空的用法都是在程序开发时常用的,相信不少同学在这种简单的问题上也吃过亏,到底有什么区别,使用有什么讲究,带着问题往下看. 二.jar包 commons-lang3-3.5 ...

  9. Chrome Developer Tools 中的 Preview 不显示 HTML 的问题

    Chrome Developer Tools 中的 Preview 不显示 HTML 的问题 最近升级到 Chrome V64,发现 Chrome Developer Tools 中的 Preview ...

  10. POJ3070 矩阵快速幂模板

    题目:http://poj.org/problem?id=3070 矩阵快速幂模板.mod写到乘法的定义部分就行了. 别忘了 I ( ) 和 i n i t ( ) 要传引用! #include< ...