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 19 49

    $课文47 嗜酒的鬼魂 481. A public house which was recently bought by Mr.Ian Thompson is up for sale. 伊恩.汤普森先 ...

  2. c++下为使用pimpl方法的类编写高效的swap函数

    swap函数是c++中一个常用的函数,用于交换两对象的值,此外还用于在重载赋值运算符中处理自赋值情况和进行异常安全性编程(见下篇),标准模板库中swap的典型实现如下: namespace stl { ...

  3. PyQt4 py2exe 打包 HardwareManager

    #!/usr/bin/env python # -*- coding: UTF-8 -*- # 1. 以下代码保存在HardwareManager项目的目录下,名称叫:setup.py: # 2. 打 ...

  4. BZOJ2124: 等差子序列(树状数组&hash -> bitset 求是否存在长度为3的等差数列)

    2124: 等差子序列 Time Limit: 3 Sec  Memory Limit: 259 MBSubmit: 2354  Solved: 826[Submit][Status][Discuss ...

  5. Spring Model存储值在jsp EL表达式中不能正确显示(原样显示)问题

    这几天我搭了一个SpringMvc环境,写了一个Controller,并且Controller里面有一个很简单的映射到jsp页面的方法,如下: 这里的Map<String,String>其 ...

  6. python基于协程的网络库gevent、eventlet

    python网络库也有了基于协程的实现,比较著名的是 gevent.eventlet 它两之间的关系可以参照 Comparing gevent to eventlet, 本文主要简单介绍一下event ...

  7. Linux下软件安装方法

    1.交叉编译: ./configure --prefix=/usr/local/XXX ...... --host=armeg:./configure --prefix=/media/ubuntu/w ...

  8. Java多线程编程核心技术,第六章

    1,饿汉模式/单例模式,一开始就新建一个静态变量,后面用getInstance()都是同一个变量 2,懒汉模式/单例模式,在getInstance()才会new一个对象,在第一个有了后不会继续创建 3 ...

  9. Ubuntu 16.04 natural scrolling

    http://ubuntuhandbook.org/index.php/2016/05/install-ubuntu-tweak-in-ubuntu-16-04/ download ubuntu-tw ...

  10. Appcan、apicloud、HBuilder 不同之处解析

    来源:http://www.mamicode.com/info-detail-1129829.html 现在Hybrid app是一中非常火热的开发模式,在国内对应的开发工具也乱象丛生,有WeX5.c ...