双指针法删除元素,保证时间复杂度O(n)
#include
#include
#include
using namespace std;
class Solution {
public:
int removeElement(vector
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (val != nums[fastIndex]) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};
int main() {
vector
Solution s;
s.removeElement(vec,3);
for (int i = 0; i < vec.size()-1; i++) {
cout << vec[i]<
}