题目描述:(. - 力扣(LeetCode))
核心思想:数组元素的删除其实就是覆盖,暴力解法也好双指针也好。
//常规双指针
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int write = 0;
int len = nums.size();
for (int read = 0; read < len; read++) {//读指针,读取符合要求的数组元素
if (nums[read] == val) continue;
nums[write++] = nums[read];//写指针,跟着读指针的后脚,覆盖符合条件的元素
}
return write;//刚好是数组的长度
}
};
//官网的优化双指针
//其实思路是一样的,符合条件的元素就读取,写下覆盖
//这种解法打乱了原本的元素排序
//可以避免 1 2 3 4 5 删除val = 1 重复赋值操作
//感觉还是上面的解法更好
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int left = 0;
int right = nums.size();
while (left < right) {
if (nums[left] == val) {
nums[left] = nums[right-1];
right--;
}
else {
left++;
}
}
return left;
}
};