题目描述:移除数组中数位
val
的元素,并返回一个长度,前长度个元素不包括该元素val
.
题目链接:Leetcode 27. Remove Element
思路和前面一题的思路一样,那就是判断是否相等,然后从0下标开始置位移动。
代码如下
class Solution {
public int removeElement(int[] nums, int val) {
int cnt = 0;
for (int idx = 0; idx < nums.length; idx++) {
if (nums[idx] != val){
nums[cnt++] = nums[idx];
}
}
return cnt;
}
}