[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 = 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]
]
解法1:
在 3Sum 的基础上再加一层循环即可,3Sum 时间复杂度为 O(n2),所以这个方法时间复杂度为 O(n3)。
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 4) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int sum3 = target - nums[i]; // 后3个数之和需等于sum3
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int sum2 = sum3 - nums[j]; // 后2个数之和需等于sum3
int left = j + 1, right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] == sum2) {
List<Integer> quad = new ArrayList<>();
quad.add(nums[i]);
quad.add(nums[j]);
quad.add(nums[left]);
quad.add(nums[right]);
res.add(quad);
while (left < right && nums[left++] == nums[left]) {}
while (left < right && nums[right--] == nums[right]) {}
} else if (nums[left] + nums[right] < sum2) {
while (left < right && nums[left++] == nums[left]) {}
} else {
while (left < right && nums[right--] == nums[right]) {}
}
}
}
}
return res;
}
}
解法2:
先排序 (O(nlogn)),然后遍历整个数组,以每两个数的和作为key将两个数的index存于HashMap中,由于存在和相同的情况,因此HashMap中的每个键对应的是一个List,每个List中保存着多组index对,这一操作时间复杂度为 (O(n2))。
遍历每个key,计算出需要满足4Sum为target的另外一个2Sum,两个2Sum对应的List分别为listA和listB,遍历其中的每一组index,分别为[a0, a1] 和 [b0, b1]。为避免找到index重复的结果,只寻找满足 a0 < b0, a0 < b1, a1 < b0, a1 < b1 的结果,而因为本身就有 a0 < a1, b0 < b1,所以只需满足 a1 < b0 即可。判断找到的结果是否已存在,不存在再把结果加到res中。这一操作比较复杂,时间复杂度不好算,据说是(O(n2logn)),但LeetCode给出的结果是超时。。。。
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 4) {
return res;
}
Arrays.sort(nums);
HashMap<Integer, List<Integer[]>> map = new HashMap<>();
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
int sum = nums[i] + nums[j];
Integer[] pair = {i, j};
if (!map.containsKey(sum)) {
map.put(sum, new ArrayList<Integer[]>());
}
map.get(sum).add(pair);
}
}
Set<Integer> keys = map.keySet();
for (int key : keys) {
List<Integer[]> listA = map.get(key);
List<Integer[]> listB = map.get(target - key);
if (listA != null && listB != null) {
for (Integer[] pairA : listA) {
int a0 = pairA[0], a1 = pairA[1];
for (Integer[] pairB : listB) {
int b0 = pairB[0], b1 = pairB[1];
if (a1 < b0) { // 因为肯定存在: a0 < a1, b0 < b1
List<Integer> list = new ArrayList<>();
list.add(nums[a0]);
list.add(nums[a1]);
list.add(nums[b0]);
list.add(nums[b1]);
if (!res.contains(list)) res.add(list);
}
}
}
}
}
return res;
}
}
[LeetCode] 18. 4Sum ☆☆的更多相关文章
- [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 ...
- LeetCode——18. 4Sum
一.题目链接:https://leetcode.com/problems/4sum/ 二.题目大意: 给定一个数组A和一个目标值target,要求从数组A中找出4个数来使之构成一个4元祖,使得这四个数 ...
- LeetCode 18 4Sum (4个数字之和等于target)
题目链接 https://leetcode.com/problems/4sum/?tab=Description 找到数组中满足 a+b+c+d=0的所有组合,要求不重复. Basic idea is ...
- 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 ...
- leetcode 15 3sum & leetcode 18 4sum
3sum: 1 class Solution { public: vector<vector<int>> threeSum(vector<int>& num ...
- 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 ...
- Java [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 ...
- C#解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 ...
- [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 ...
随机推荐
- leetcode个人题解——#24 Swap Nodes in Pairs
因为不太熟悉链表操作,所以解决方法烦了点,空间时间多有冗余. 代码中l,r分别是每一组的需要交换的左右指针,temp是下一组的头指针,用于交换后链接:res是交换后的l指针,用于本组交换后尾指针在下一 ...
- 软件工程课堂作业(一)——随机产生四则运算题目(C++)
一.设计思想: 1.首先主函数只用来调用随机产生并输出运算题目函数,随机产生并输出这一部分功能用一个randout函数实现: 2.随机产生运算数这一功能,两个运算数可以用随机函数生成,并将它们控制在1 ...
- 如何修改git push时的密码
如何修改git push时的密码 如下: 打开git bash 输入 cd ~/.ssh ls 确定有 id_rsa 和 id_rsa.pub文件 ssh-keygen -p -f id_rsa 第一 ...
- [git]基本用法1
一.实验说明 本节实验为 Git 入门第一个实验,可以帮助大家熟悉如何创建和使用 git 仓库. 二.git的初始化 在使用git进行代码管理之前,我们首先要对git进行初始化. 1.Git 配置 使 ...
- 编译android6.0错误recipe for target 'out/host/linux-x86/obj/lib/libart.so' failed
转自:http://blog.csdn.net/ztguang/article/details/52856076 trip: libpagemap_32 (out/target/product/xx/ ...
- JAVA学习之HashCode
public native int hashCode(); 返回该对象的哈希码值.支持此方法是为了提高哈希表(例如 java.util.Hashtable 提供的哈希表)的性能. 一.HashCode ...
- VS2012完全卸载
1.先交VS2012的ISO通过Ultraiso载入2.DOS命中输入 I:\vs_ultimate.exe /uninstall /force 或 I:vs_ultimate.exe /uninst ...
- Java序列简单使用
package javatest; import java.io.*; public class SerializableTest implements Serializable { public s ...
- BZOJ4813 CQOI2017小Q的棋盘(树形dp)
设f[i][j]为由i号点开始在子树内走j步最多能经过多少格点,g[i][j]为由i号点开始在子树内走j步且回到i最多能经过多少格点,转移显然. #include<iostream> #i ...
- 【HUD-5790】Prefix (主席树+tire)
似乎是归队赛的最后一道题. 由于当时以为是公共字串所以没写555555,其实是求公共前缀. 做法是建立tire,把tire上的点编号看成是值,查询第l到第r个字符串的区间内不重复的值的个数.建立主席树 ...