1.题目描述
2.解题思路
拷贝覆盖:
主要思路是遍历数组 nums,每次取出的数字变量为 nums[j],同时设置一个下标 i
在遍历过程中如果出现数字与需要移除的值不相同时,则进行拷贝覆盖 nums[i] = nums[j],i 自增 1
如果相同的时候,则跳过该数字不进行拷贝覆盖,最后 i 即为新的数组长度
3.代码实现
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for(int j=0;j <nums.length;j++) {
if(nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
}