问题描述
使用C++实现数组中指定元素的删除。
#include <iostream>
#include <vector>
using namespace std;
int removeElement(vector<int> & list, int target);
ostream & operator<<(ostream & os, const vector<int> & list);
int main() {
vector<int> list = {1,2,3,2,2,3,6,2,7};
int slow = removeElement(list, 2);
for (int i = slow; i < list.size(); ++i)
list[i] = 0;
cout << slow << endl;
cout << list;
return 0;
}
int removeElement(vector<int> & list, int target) {
int fast = 0;
int slow = 0;
while (fast < list.size()) {
if (list[fast] != target) {
list[slow] = list[fast];
slow++;
}
fast++;
}
return slow;
}
ostream & operator<<(ostream & os ,const vector<int> & list) {
int i = 0;
cout << "{";
for (i = 0; i < list.size() - 1; ++i) {
cout << list[i] << ", ";
}
cout << list[i];
cout << "}" << endl;
return os;
}
代码分析:
首先,我们定义两个指针fast和slow,当fast指针指向的元素不等于目标元素时,便将fast指向元素的值赋值给slow指针指向的值,此时slow和fast向后移动一位。这样,当slow指向target时,target便被其后面的值覆盖,便实现了指定元素的删除。最后的slow表示删除指定元素后数组的元素个数(以0为初始值),如果我们将slow以后的元素全部赋值为0,便实现了删除指定元素后数组的前移(以0补充)。