【发布时间】:2020-08-03 00:32:03
【问题描述】:
我在 cpp 中有 2 个向量:[1,2,2,1] 和 [2,2]。我希望交叉点是:[2,2]。这是我实现的算法,但我得到了堆溢出,我不知道为什么。有人可以向我解释发生了什么问题吗?
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
//This is the intersection we will return
vector<int> out;
//If either array's are empty the intersection is empty
if(nums1.size() == 0 || nums2.size() == 0) return out;
//Iterate through first array, then go through each element of second array. After the end of each iteration we pop_front of first array. (Change to while loop)
for(int i = 0; i < nums1.size(); nums1.erase(nums1.begin())){
//flag to break out of second array iteration
bool flag = false;
int j = 0;
while (!flag){
if(nums1[i] == nums2[j]){
//Append the answer to the output. Doesn't matter if it is from array 1 or 2 they are equal
out.push_back(nums1[i]);
//I want to erase the element in the second array that was matched in the first array to insure that no integer is matched in the next iteration of the first array. (Heap buffer overflow??)
nums2.erase(nums2.begin()+j);
//If a match was found we break out of the second array iteration
flag = true;
}
//Check if index j is out of bounds, if it is we have reached the end of the second array
if(j == nums2.size() - 1){
flag = true;
}
j++;
}
}
return out;
}
};
我想知道为什么我不能擦除第二个数组中与第一个数组中的元素匹配的元素。
【问题讨论】:
-
两次调用
std::sort和一次调用std::set_intersection就足够了——基本上是3 行代码。不需要你现在拥有的所有代码。 -
顺便说一句,您可能希望传入
nums2的副本而不是参考。否则,您的删除将影响原件,这可能会使调用者无休止:-) 而且,任何时候您传递一个您不想想要更改的效率参考(即,nums1),应该是const。 -
方法头由 Leetcode 提供。
-
LC 上的许多人似乎相信,如果您使用内置抽象,您就是在“作弊”。如果我正在雇用一名开发人员,我宁愿雇用一个知道如何在适当的时候使用库的人,而不是滚动他们自己的(通常是缓慢和错误的)重新实现。另外,你在哪里画线? C++ 已经是一种高级语言,具有像
vector这样的高级抽象。这个想法是vector是允许的,而set_intersection不是让我觉得樱桃采摘。 IRL 你也永远不会重新实现,它们基本上存在于大致相同的抽象级别。
标签: c++ arrays algorithm vector