mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
fix: 修正 0015.三数之和.md 中的严重表述错误
This commit is contained in:
@ -50,36 +50,49 @@
|
|||||||
```CPP
|
```CPP
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
|
// 在一个数组中找到3个数形成的三元组,它们的和为0,不能重复使用(三数下标互不相同),且三元组不能重复。
|
||||||
|
// 理论解法:a+b+c(存储)==0(检索) <=> c(存储)==0-(a+b)(检索)
|
||||||
|
// 实际解法:a+b+c(存储)==0(检索) <=> b(存储)==0-(a+c)(检索)
|
||||||
vector<vector<int>> threeSum(vector<int>& nums) {
|
vector<vector<int>> threeSum(vector<int>& nums) {
|
||||||
vector<vector<int>> result;
|
// 本解法的内层循环一边存储一边检索,所以被存储的应该是b,而不是c
|
||||||
|
vector<vector<int>> res;
|
||||||
sort(nums.begin(), nums.end());
|
sort(nums.begin(), nums.end());
|
||||||
// 找出a + b + c = 0
|
|
||||||
// a = nums[i], b = nums[j], c = -(a + b)
|
// 如果只有正数,不可能形成和为0的三元组
|
||||||
|
if (nums[0] > 0)
|
||||||
|
return res;
|
||||||
|
|
||||||
for (int i = 0; i < nums.size(); i++) {
|
for (int i = 0; i < nums.size(); i++) {
|
||||||
// 排序之后如果第一个元素已经大于零,那么不可能凑成三元组
|
// [a, a, ...] 如果本轮a和上轮a相同,那么找到的b,c也是相同的,所以去重a
|
||||||
if (nums[i] > 0) {
|
if (i > 0 && nums[i] == nums[i - 1])
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (i > 0 && nums[i] == nums[i - 1]) { //三元组元素a去重
|
|
||||||
continue;
|
continue;
|
||||||
}
|
|
||||||
unordered_set<int> set;
|
// 这个st的作用是存储b
|
||||||
for (int j = i + 1; j < nums.size(); j++) {
|
unordered_set<int> st;
|
||||||
if (j > i + 2
|
|
||||||
&& nums[j] == nums[j-1]
|
for (int k = i + 1; k < nums.size(); k++) {
|
||||||
&& nums[j-1] == nums[j-2]) { // 三元组元素b去重
|
// [(-2x), ..., (x), (x), x, x, x, ...]
|
||||||
|
// eg. [0, 0, 0]
|
||||||
|
// eg. [-4, 2, 2]
|
||||||
|
// eg. [(-4), -1, 0, 0, 1, (2), (2), {2}, {2}, 3, 3]
|
||||||
|
// 去重b=c时的b和c,即第三个x到最后一个x需要被跳过
|
||||||
|
if (k > i + 2 && nums[k] == nums[k - 1] && nums[k - 1] == nums[k - 2])
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
|
// a+b+c=0 <=> b=0-(a+c)
|
||||||
|
int target = 0 - (nums[i] + nums[k]);
|
||||||
|
if (st.find(target) != st.end()) {
|
||||||
|
res.push_back({nums[i], target, nums[k]}); // nums[k]成为c
|
||||||
|
// 内层循环中,a固定,如果find到了和上轮一样的b,那么c也就和上轮一样,所以去重b
|
||||||
|
st.erase(target);
|
||||||
}
|
}
|
||||||
int c = 0 - (nums[i] + nums[j]);
|
else {
|
||||||
if (set.find(c) != set.end()) {
|
st.insert(nums[k]); // nums[k]成为b
|
||||||
result.push_back({nums[i], nums[j], c});
|
|
||||||
set.erase(c);// 三元组元素c去重
|
|
||||||
} else {
|
|
||||||
set.insert(nums[j]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result;
|
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user