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. 集成学习之Boosting —— Gradient Boosting原理

    集成学习之Boosting -- AdaBoost原理 集成学习之Boosting -- AdaBoost实现 集成学习之Boosting -- Gradient Boosting原理 集成学习之Bo ...

  2. phalcon 设置cookie一直是httponly导致前端读取不到cookie的值

    解决办法: 修改配置如果不好使,则暂时降低phalcon版本为3.1.2. 注意设置cookie的参数secure的值为false,否则js还是读取不到cookie

  3. 总线设备驱动模型---platform篇

    总线设备驱动模型----驱动篇 http://blog.chinaunix.net/uid-27664726-id-3334923.html http://blog.chinaunix.net/uid ...

  4. Qt Creator 模块QtSql

    在新建Qt Gui Application时,没有弹出模块选择页, 可以手动在pro文件中增加. 比如要选中QtSql模块,(目前我没有找到哪里可以修改要选中的模块), 我是手动在pro文件中增加了一 ...

  5. GPU编程自学7 —— 常量内存与事件

    深度学习的兴起,使得多线程以及GPU编程逐渐成为算法工程师无法规避的问题.这里主要记录自己的GPU自学历程. 目录 <GPU编程自学1 -- 引言> <GPU编程自学2 -- CUD ...

  6. HDU 3986

    http://acm.hdu.edu.cn/showproblem.php?pid=3986 从开始的最短路里依次删一条边,求新的最短路,求最长的最短路 删边操作要标记节点以及节点对应的边 #incl ...

  7. ubuntu16.04 源码安装Python3.7 (可以在此基础上安装Tensorflow) (确保Tensorflow计算框架与系统的彻底隔离)

    Python3.7 源码下载: https://www.python.org/downloads/release/python-370/ 解压源码: tar -zxvf Python-3.7.0.tg ...

  8. 實驗項目wordcount

    wordcount 1.设计思路 第一步 :主函数参数使用命令行参数,定义一个文件指针fp. 第二步:判断能否用只读的形式打开命令行指针中的文件,并让指针指向打开函数,若不能则输出不能读取文件,否则下 ...

  9. Tomcat调优总结(Tomcat自身优化、Linux内核优化、JVM优化)

    Tomcat自身的调优是针对conf/server.xml中的几个参数的调优设置.首先是对这几个参数的含义要有深刻而清楚的理解.以tomcat8.5为例,讲解参数. 同时也得认识到一点,tomcat调 ...

  10. 毕业了-java二叉树层次遍历算法

    /*************************************** * 时间:2017年6月23日 * author:lcy * 内容:二叉树的层次遍历 * 需要借助队列这个数据结构,直 ...