【LeetCode】 18. 4Sum 四数之和(Medium)(JAVA)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【LeetCode】 18. 4Sum 四数之和(Medium)(JAVA),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2453字,纯文字阅读大概需要4分钟。
内容图文
![【LeetCode】 18. 4Sum 四数之和(Medium)(JAVA)](/upload/InfoBanner/zyjiaocheng/641/b35c06e66e6b438b97c9065cdcf1b769.jpg)
【LeetCode】 18. 4Sum 四数之和(Medium)(JAVA)
题目地址: https://leetcode.com/problems/4sum/
题目描述:
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.
Example:
Given array nums = [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]
]
题目大意
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
解题方法
和三数只和一样,只是多了一层循环 【LeetCode】 15. 3Sum 三数之和(Medium)(JAVA)
对时间进行了优化,直接过大或者过小直接返回,节省了一半时间
if (pre + nums[nums.length - 1] < target || pre + nums[k + 1] > target) continue;
也可以继续优化时间,在每层 for 循环里多个判断
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length < 4) return res;
Arrays.sort(nums);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer temp = map.get(nums[i]);
if (temp == null) {
map.put(nums[i], 1);
} else {
map.put(nums[i], temp + 1);
}
}
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
for (int k = j + 1; k < nums.length - 1; k++) {
if (k > j + 1 && nums[k] == nums[k - 1]) continue;
int pre = nums[i] + nums[j] + nums[k];
if (pre + nums[nums.length - 1] < target || pre + nums[k + 1] > target) continue;
int four = target - pre;
if (four < nums[k]) continue;
Integer count = map.get(four);
if (count == null) continue;
if (nums[k] == four && nums[k] > nums[j]) {
if (count < 2) continue;
}
if (nums[k] == four && nums[k] == nums[j] && nums[j] > nums[i]) {
if (count < 3) continue;
}
if (nums[k] == four && nums[k] == nums[j] && nums[j] == nums[i]) {
if (count < 4) continue;
}
List<Integer> cur = new ArrayList<>();
cur.add(nums[i]);
cur.add(nums[j]);
cur.add(nums[k]);
cur.add(four);
res.add(cur);
}
}
}
return res;
}
}
执行用时 : 25 ms, 在所有 Java 提交中击败了 52.37% 的用户
内存消耗 : 41.4 MB, 在所有 Java 提交中击败了 11.81% 的用户
内容总结
以上是互联网集市为您收集整理的【LeetCode】 18. 4Sum 四数之和(Medium)(JAVA)全部内容,希望文章能够帮你解决【LeetCode】 18. 4Sum 四数之和(Medium)(JAVA)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。