27、移除元素
题目链接
概述:移除数组中所有等于val的元素,并返回新数组的长度
解题思路:
1、暴力求解
使用for循环遍历数组,找到待删除的值,然后使用一个新的for循环遍历该值之后的所有数组元素,全部前移一个位置
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
for(int i = 0; i < size; i++){
if(nums[i] == val){
for(int j = i+1; j < size; j++){
nums[j-1] = nums[j];
}
i--;
size--;
}
}
return size;
}
2、双指针
使用快指针寻找新的数组元素,使用慢指针记录新数组的长度
本质:遍历val之后的数组元素,全部前移一个位置,覆盖掉val
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];
slowIndex++;
}
}
return slowIndex;
}