题目:

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: 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]
]

题解:

  这个题与3Sum类似,求4Sum就在原基础上再加上一层循环就可以了。这里只给出此种解法思路的其中一个解法。

Solution 1 (36ms)

 class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> sv;
sort(nums.begin(), nums.end());
int n = nums.size(); for(int i=; i<n-; i++) {
for(int j=i+; j<n-; j++) {
int k = j+, l = n-;
int a = nums[i], b = nums[j];
while(k<l) {
int c = nums[k], d = nums[l];
if(a+b+c+d == target) {
sv.insert({a,b,c,d});
k++;
l--;
}
else if(a+b+c+d < target) k++;
else l--;
}
}
}
return vector<vector<int>> (sv.begin(),sv.end());
}
};

  还有一种解法,也是利用了3Sum,不过不是再加一层循环,而是直接调用3Sum函数:取nums[i],然后对后续剩余数组元素求3Sum,tar为target - nums[i];

Solution 2 (32ms)

 class Solution {
public:
vector<vector<int> > threeSum(vector<int> &nums, int target) {
set<vector<int>> sv;
sort(nums.begin(), nums.end());
int n = nums.size(); for(int i=; i<n-; i++) {
int a = nums[i];
int j = i+, k = n-;
while(j<k) {
int b = nums[j], c = nums[k];
if(a+b+c == target) {
sv.insert({a,b,c});
j++;
k--;
}
else if(a+b+c > target) k--;
else j++;
}
}
return vector<vector<int>> (sv.begin(),sv.end());
}
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> vv;
sort(nums.begin(), nums.end());
int n = nums.size(); for(int i=; i<n-; i++) {
if(i> && nums[i] == nums[i-]) continue;
//截取剩余数组
vector<int> v(nums.begin()+i+,nums.end());
vector<vector<int>> tmp = threeSum(v, target - nums[i]);
for(int j=; j<tmp.size(); j++) {
tmp[j].insert(tmp[j].begin(), nums[i]);
vv.push_back(tmp[j]);
}
}
return vv;
}
};

  还有一种更为优化的解法,思路是一致的,只是加了一个小技巧:在两个外循环中先判断四个值的和与target的大小,即

  if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;
  if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;

  通过这两条语句减少了搜索时间,不必进入内循环判断;对于j同理。

Solution 3 (12ms)

 class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> sv;
sort(nums.begin(), nums.end());
int n = nums.size();
if(n<) return vector<vector<int>> (sv.begin(),sv.end());
for(int i=; i<n-; i++) {
if(nums[i]+nums[i+]+nums[i+]+nums[i+]>target) break;
if(nums[i]+nums[n-]+nums[n-]+nums[n-]<target) continue;
if(i>&&nums[i]==nums[i-]) continue;
for(int j=i+; j<n-; j++) {
if(j>i+&&nums[j]==nums[j-]) continue;
if(nums[i]+nums[j]+nums[j+]+nums[j+]>target) break;
if(nums[i]+nums[j]+nums[n-]+nums[n-]<target) continue;
int k = j+, l = n-;
int a = nums[i], b = nums[j];
while(k<l) {
int c = nums[k], d = nums[l];
if(a+b+c+d == target) {
sv.insert({a,b,c,d});
k++;
l--;
}
else if(a+b+c+d < target) k++;
else l--;
}
}
}
return vector<vector<int>> (sv.begin(),sv.end());
}
};

Solution 4

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for(int i = ; i < n - ; ++i){
for(int j = i + ; j < n - ; ++j){
int begin = j + , end = n - ;
while(begin < end){
int sum = nums[i] + nums[j] + nums[begin] + nums[end];
if(sum == target)
res.push_back({nums[i], nums[j], nums[begin++], nums[end--]});
else if (sum < target)
++begin;
else
--end;
}
}
}
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
};

去重的另一种方法, 使用了algorithm

Solution 5

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
vector<vector<int>> res;
sort(nums.begin(), nums.end());
unordered_multimap<int, pair<int, int>> map;
for(int i = ; i < n - ; ++i){
for(int j = i + ; j < n; ++j){
map.insert(make_pair(nums[i] + nums[j], make_pair(i, j)));
}
}
for(auto i = map.begin(); i != map.end(); ++i){
int val = target - i->first;
auto range = map.equal_range(val);
for(auto j = range.first; j != range.second; ++j){
auto a = i->second.first, b = i->second.second;
auto c = j->second.first, d = j->second.second;
if(a != c && a != d && b != c && b != d){
vector<int> tmp = {nums[a], nums[b], nums[c], nums[d]};
sort(tmp.begin(), tmp.end());
res.push_back(tmp);
}
}
}
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
};

先缓存两个数的和,注意要使用multimap(from 九章算法)

【LeetCode】018 4Sum的更多相关文章

  1. 【LeetCode】18. 4Sum 四数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...

  2. 【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  ...

  3. 【LeetCode】454. 4Sum II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcod ...

  4. 【LeetCode】16. 4Sum

    题目:Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...

  5. 【LeetCode】18. 4Sum

    题目: 思路:这题和15题很像,外层再加一个循环稍作修改即可 public class Solution { public List<List<Integer>> fourSu ...

  6. 【LeetCode】454 4Sum II

    题目: Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are su ...

  7. 【LeetCode】 454、四数之和 II

    题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...

  8. 【LeetCode】18、四数之和

    题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...

  9. 【leetcode】963. Minimum Area Rectangle II

    题目如下: Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from ...

随机推荐

  1. 解决 SVN版本冲突

    链接:http://blog.csdn.net/windone0109/article/details/4857044 版本冲突原因: 假设A.B两个用户都在版本号为100的时候,更新了kingtun ...

  2. nginx学习之压缩解压篇(七)

    1.简介 压缩响应可以减少传输数据的大小,节省带宽.但过多的压缩会造成很大的处理开销.在发送给客户端之前,nginx会对响应做压缩,但是如果后端服务器已经 压缩过了,nginx就不再压缩. 2.开启压 ...

  3. spring mvc注解和spring boot注解

    1 spring mvc和spring boot之间的关系 spring boot包含spring mvc.所以,spring mvc的注解在spring boot总都是可以用的吗? spring b ...

  4. 【python】-- 面向对象引子、概念

    面向过程编程 1.编程范式 编程是 程序 员 用特定的语法+数据结构+算法组成的代码来告诉计算机如何执行任务的过程 , 一个程序是程序员为了得到一个任务结果而编写的一组指令的集合,正所谓条条大路通罗马 ...

  5. spark 在yarn执行job时一直抱0.0.0.0:8030错误

    近日新写完的spark任务放到yarn上面执行时,在yarn的slave节点中一直看到报错日志:连接不到0.0.0.0:8030 . The logs are as below: 2014-08-11 ...

  6. 搜索ABAP程序代码中的字符串

    标准程序名:RPR_ABAP_SOURCE_SCAN /BEV1/NERM07DOCS

  7. QT里面的delay使用

    void delay() { QTime dieTime= QTime::currentTime().addSecs(1); while( QTime::currentTime() < dieT ...

  8. 关于Unicode转为str的方法

    unicode_a=u'\u810f\u4e71' str_a=unicode_a.encode('unicode-escape').decode('string_escape')

  9. Python基础(3)_可变对象与不可变对象、列表、元祖和字典

    可变对象与不可变对象 实例被创建后,身份和类型是不可变的, 如果值是不可以被修改的,则是不可变对象 如果值是可以被修改的,则是可变对象 #在id不动,type也不动,value被修改了,则称为可变 # ...

  10. iOS 屏幕原点坐标 && 导航栏风格的自定义

    其一 屏幕原点坐标 (x ,y) 受 self.navigationController. navigationBar 的 setTranslucent (BOOL) 属性控制 在 iOS7 以后   ...