У меня есть 2 вектора в 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 < 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;
}
};
Я хочу знать, почему я не могу стереть элемент во втором массиве, который соответствует элементу в первом массиве.