4Sum (M)
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]
]
题意
求四元组使其之和等于指定值。
思路
仿照 15. 3Sum 的方法:先对数组排序,依次固定前两个元素i、j,对后两个元素m、n使用two pointers,注意去除重复值,时间复杂度为O(N3)。
另一种方法:先预处理两个数的和,存入hash表中,再重新二重循环求两数的和sum,看能否在hash表中找到值为target-sum的key,理论上复杂度为O(N2),但考虑到去重步骤,实际时间还会增加。
代码实现 - O(N3)
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
// 去除重复的i
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
// 去除重复的j
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int m = j + 1, n = nums.length - 1;
while (m < n) {
int sum = nums[i] + nums[j] + nums[m] + nums[n];
if (sum < target) {
m++;
while (m < n && nums[m] == nums[m - 1]) {
m++;
}
} else if (sum > target) {
n--;
while (m < n && nums[n] == nums[n + 1]) {
n--;
}
} else {
List<Integer> quaternion = new ArrayList<>();
quaternion.add(nums[i]);
quaternion.add(nums[j]);
quaternion.add(nums[m]);
quaternion.add(nums[n]);
ans.add(quaternion);
m++;
while (m < n && nums[m] == nums[m - 1]) {
m++;
}
n--;
while (m < n && nums[n] == nums[n + 1]) {
n--;
}
}
}
}
}
return ans;
}
}
**代码实现 - 散列处理 **
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
Map<Integer, List<Pair>> hash = new HashMap<>();
Arrays.sort(nums);
// 生成hash表
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
// 若hash中存在
if (hash.containsKey(nums[i] + nums[j])) {
boolean flag = true;
// 同元素组成的sum只保留x最大的下标对
for (Pair pair : hash.get(nums[i] + nums[j])) {
if (nums[pair.x] == nums[i]) {
pair.x = i;
pair.y = j;
flag = false;
break;
}
}
if (flag) {
hash.get(nums[i] + nums[j]).add(new Pair(i, j));
}
} else {
List<Pair> pair = new ArrayList<>();
pair.add(new Pair(i, j));
hash.put(nums[i] + nums[j], pair);
}
}
}
for (int i = 0; i < nums.length - 3; i++) {
// 去除重复的i
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
// 去除重复的j
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int sum = nums[i] + nums[j];
if (hash.containsKey(target - sum)) {
for (Pair pair : hash.get(target - sum)) {
// 只记录下标排在j后面的元素
if (pair.x > j) {
List<Integer> quaternion = Arrays.asList(nums[i], nums[j], nums[pair.x], nums[pair.y]);
ans.add(quaternion);
}
}
}
}
}
return ans;
}
private class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
本文深入探讨了4Sum问题的两种解决策略,一是基于排序和双指针技术的时间复杂度为O(N^3)的方法,二是利用哈希表进行预处理,理论上时间复杂度为O(N^2)的解决方案。通过具体代码实现,展示了如何避免重复解,适用于算法学习和面试准备。
2312

被折叠的 条评论
为什么被折叠?



