Given an array S of n integers, are there elements a, b, c, 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, abcd)
  • 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)

LeetCode 中关于数字之和还有其他几道,分别是 Two Sum ,3Sum ,3Sum Closest,虽然难度在递增,但是整体的套路都是一样的,在这里为了避免重复项,我们使用了 STL 中的 TreeSet,其特点是不能有重复,如果新加入的数在 TreeSet 中原本就存在的话,插入操作就会失败,这样能很好的避免的重复项的存在。此题的 O(n^3) 解法的思路跟 3Sum 基本没啥区别,就是多加了一层 for 循环,其他的都一样,代码如下:

解法一:

class Solution {
public:
vector<vector<int>> fourSum(vector<int> &nums, int target) {
set<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = ; i < int(nums.size() - ); ++i) {
for (int j = i + ; j < int(nums.size() - ); ++j) {
if (j > i + && nums[j] == nums[j - ]) continue;
int left = j + , right = nums.size() - ;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
vector<int> out{nums[i], nums[j], nums[left], nums[right]};
res.insert(out);
++left; --right;
} else if (sum < target) ++left;
else --right;
}
}
}
return vector<vector<int>>(res.begin(), res.end());
}
};

但是毕竟用 TreeSet 来进行去重复的处理还是有些取巧,可能在 Java 中就不能这么做,那么还是来看一种比较正统的做法吧,手动进行去重复处理。主要可以进行的有三个地方,首先在两个 for 循环下可以各放一个,因为一旦当前的数字跟上面处理过的数字相同了,那么找下来肯定还是重复的。之后就是当 sum 等于 target 的时候了,在将四个数字加入结果 res 之后,left 和 right 都需要去重复处理,分别像各自的方面遍历即可,参见代码如下:

解法二:

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

Github 同步地址:

https://github.com/grandyang/leetcode/issues/18

类似题目:

Two Sum

3Sum

4Sum II

参考资料:

https://leetcode.com/problems/4sum/

https://leetcode.com/problems/4sum/discuss/8549/My-16ms-c%2B%2B-code

https://leetcode.com/problems/4sum/discuss/8575/Clean-accepted-java-O(n3)-solution-based-on-3sum

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 18. 4Sum 四数之和的更多相关文章

  1. [leetcode]18. 4Sum四数之和

    Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums s ...

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

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

  3. 【LeetCode 18】四数之和

    题目链接 [题解] 两重循环枚举[i..j]这个区间 同时规定必取nums[i]和nums[j] 那么现在的问题就变成在下标为[i..j]这个区间的数字里面找两个数字使他们的和为target-nums ...

  4. Leetcode(18)-四数之和

    给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满 ...

  5. 【LeetCode】18、四数之和

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

  6. [LeetCode] 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 ...

  7. [LeetCode] 454. 4Sum II 四数之和II

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

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

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

  9. Java实现 LeetCode 18 四数之和

    18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target ...

随机推荐

  1. redis命令之 ----key(键)

    DEL DEL key [key ...] 删除给定的一个或多个 key . 不存在的 key 会被忽略. DUMP DUMP key 序列化给定 key ,并返回被序列化的值,使用 RESTORE  ...

  2. python asyncio call_soon, call_at, call_later

    1. call_soon, 协程一运行就马上运行 def callback(sleep_times): print("success time {}".format(sleep_t ...

  3. 后端必备的 Git 分支开发规范指南 转

    原文链接 作者:稻草叔叔 http://juejin.im/post/5b4328bbf265da0fa21a6820 点击上方 "后端技术精选",选择 "置顶公众号&q ...

  4. Java8新特性——StreamAPI 的使用

    StreamAPI的说明 Java8中有两大最为重要的改变.第一个是 Lambda 表达式:另外一个则是 Stream API. Stream API ( java.util.stream) 把真正的 ...

  5. ansible碎碎念

    1. Using a SSH password instead of a key is not possible because Host Key checking is enabled and ss ...

  6. @Valid 数据校验 + 自定义全局异常信息

    关于javax.validation.Validator校验的使用 对于要校验的实体类:其需要校验的字段上需要添加注解 实际例子 使用:首先要拿到 validator的子类 Validator val ...

  7. 基于Task定时检测网络本地网络状况

    首先我们需要使用winInet.dll中的InternetGetConnectedState方法来检测本地是否连接网络,然后再通过ping的方式来获取网络状况. 然后我们采用Task来开辟一个线程来定 ...

  8. javascript:警告(alert 消息对话框),确认(confirm 消息对话框)

    原文:https://blog.csdn.net/u012110719/article/details/41926315

  9. 谈谈JavaScript Navigator 对象属性

    Navigator 对象属性 可以在Navigator对象上使用以下属性: 属性 描述 appCodeName 返回浏览器的代码名称 appName 返回浏览器的名称 appVersion 返回浏览器 ...

  10. centos下非yum方式安装docker环境

    1.下载docker源码包 docker官网地址: https://download.docker.com/linux/static/stable/ 选择.tgz的包下载,例如:https://dow ...