找到两个向量的交集算法批判/解释



我在cpp中有两个向量:[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 &lt 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;
}
};

我想知道为什么我不能擦除第二个数组中与第一个数组中的元素匹配的元素。

如果nums2nums1之前变空,则程序通过访问nums2[0]显示未定义的行为。超出界限的索引。

最新更新