双指针法删除元素,保证时间复杂度O(n)
作者:互联网
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (val != nums[fastIndex]) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};
int main() {
vector<int> vec{1,4,3,1,5,76,1,5};
Solution s;
s.removeElement(vec,3);
for (int i = 0; i < vec.size()-1; i++) {
cout << vec[i]<<endl;
}
}
标签:slowIndex,删除,nums,int,复杂度,fastIndex,++,vec,指针 来源: https://www.cnblogs.com/jojocode/p/16310042.html