[英]Leetcode 4 sum problem , couldn't find whats wrong with my solution
Problem: Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < na, b, c, and d are distinct.问题:给定一个包含 n 个整数的数组 nums,返回一个包含所有唯一四元组 [nums[a]、nums[b]、nums[c]、nums[d]] 的数组,使得:0 <= a, b, c , d < na, b, c, 和 d 是不同的。 nums[a] + nums[b] + nums[c] + nums[d] == target
nums[a] + nums[b] + nums[c] + nums[d] == 目标
My code is returning duplicates, even I am skipping them.我的代码正在返回重复项,即使我正在跳过它们。 (when I run on my machine it skips the duplicate case) Array [-5,5,4,-3,0,0,4,-2] Target 4
(当我在我的机器上运行时,它会跳过重复的大小写) Array [-5,5,4,-3,0,0,4,-2] Target 4
Output
[[-5,5,4,0],[-5,5,0,4],[5,4,-3,-2],[5,-3,4,-2]]
Expected
[[-5,0,4,5],[-3,-2,4,5]]
// solution // 解决方案
class Solution {
public:
vector < vector < int >> fourSum(vector < int > & nums, int target) {
vector < vector < int > > ans;
int n = nums.size();
if (n < 4)
return ans;
// create a map of two sum
unordered_map < int, vector < pair < int, int > > > m;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
m[nums[i] + nums[j]].push_back(make_pair(i, j));
for (int i = 0; i < n - 1; i++) {
if (i > 0 and nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n; j++) {
if (j > i + 1 and nums[j] == nums[j - 1]) continue;
int sum = target - nums[i] - nums[j];
if (m.find(sum) != m.end()) {
for (auto it: m[sum]) {
int k = it.first;
int l = it.second;
if (k > j && l > k) {
//Skip invalid cases
if (!ans.empty() and ans.back()[0] == nums[i] and ans.back()[1] == nums[j] and ans.back()[2] == nums[k] and ans.back()[3] == nums[l]) {
continue;
}
vector < int > temp = {
nums[i],
nums[j],
nums[k],
nums[l]
};
ans.push_back(temp);
}
}
}
}
}
return ans;
}
};
If you print out in steps, you can see why and where you get duplicate.如果您分步打印出来,您可以看到重复的原因和位置。 For example,
例如,
with some 4
, you have pairs:有一些
4
,你有对:
4: [2, 4], [2, 5], [4, 6], [5, 6],
Then, with i=0, j=1
, sum = 4
, you have duplicate result like this.然后,使用
i=0, j=1
, sum = 4
,你有这样的重复结果。
i: 0 j: 1 sum: 4
k: 2 l: 4
add solution
k: 2 l: 5
skip duplicate
k: 4 l: 6
add solution
k: 5 l: 6
skip duplicate
See, you add to ans
result: (0,1,2,4)
and (0,1,4,6)
which is duplicate.看,你添加到
ans
结果: (0,1,2,4)
和(0,1,4,6)
是重复的。 Your condition to check two result is false.您检查两个结果的条件是错误的。
I think you can sort the nums
before running your solution.我认为您可以在运行解决方案之前对数字进行
nums
。 It will ignore duplicate like this.它会像这样忽略重复项。
Start with turning the array into a set.从将数组变成集合开始。 It will remove duplicates.
它将删除重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.