Reputation: 1815
I am searching for a long time on net. But no use. Please help or try to give some ideas how to solve this problem.
class Solution{
public:
int removeElement(vector<int> &nums, int val)
{
for (auto &it = nums.begin(); it != nums.end(); ++it)
{
if (*it == val)
{
it = nums.erase(it);
}
}
return nums.size();
}
};
int main(void)
{
Solution s;
vector<int> vi = { 3, 2, 2, 3 };
cout << "size = " << s.removeElement(vi, 3) << endl;
for (auto &i : vi)
{
cout << i << " ";
}
cout << endl;
return 0;
}
which are the class body and main function body of my code. But when i run it, compiler popped a window:
Upvotes: 0
Views: 696
Reputation: 75062
After erasing the last element, it
becomes nums.end()
and incrementing it is not allowed.
You shouldn't increment it
after erasing. This will also fix problem that one element is skipped after erasure.
Also the &
in auto &it = nums.begin()
should be removed because having it will make it invalid initialization of non-const reference.
Try this:
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
class Solution{
public:
int removeElement(vector<int> &nums, int val)
{
for (auto it = nums.begin(); it != nums.end();)
{
if (*it == val)
{
it = nums.erase(it);
} else
{
++it;
}
}
return nums.size();
}
};
int main(void)
{
Solution s;
vector<int> vi = { 3, 2, 3, 3, 2, 3 }; // added testcase of consecutive 3
cout << "size = " << s.removeElement(vi, 3) << endl;
for (auto &i : vi)
{
cout << i << " ";
}
cout << endl;
return 0;
}
Upvotes: 2