描述
分析一
和 26 题非常像,使用双指针法可以在 O ( N ) O(N) O(N)的复杂度完成。
使用变量 cnt 作为新数组(虚拟的,其实就是在原始数组的基础上)当前下标的记录,一旦有等于目标值的元素,就跳过这个元素,cnt 不计数;若当前元素与目标值不相等,就将当前元素放到 cnt 的位置,同时 cnt 向后挪一位,预留出下一个要填放的位置。
代码
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if(nums.empty()) return 0; // 判空,直接返回
int cnt = 0, length = nums.size();
for (int i = 0;i < length;i++) {
if (nums[i] != val) {
nums[cnt] = nums[i];
cnt++;
}
}
return cnt;
}
};
分析二
这是LeetCode官方给出的第二种方法。
题目中说数组中元素的顺序可以改变,这就意味着,当想要移除的 value 在数组中的个数很少时,可以通过将 value 和数组尾部元素交换的方式,达到移除的目的(对应的数组长度减一)。
代码
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
/*
作者:LeetCode
链接:https://leetcode-cn.com/problems/remove-element/solution/yi-chu-yuan-su-by-leetcode/
来源:力扣(LeetCode)
*/