题目
https://leetcode-cn.com/problems/remove-element/
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
代码
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for (; i < nums.length; i++) {
if (val == nums[i]) {
break;
}
}
int cur = i++;
for (; i < nums.length; i++) {
if (val != nums[i]) {
nums[cur++] = nums[i];
}
}
return cur;
}
}
结果
其他解法
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length - 1;
while (i <= n) {
// drd notes: 找到某个等于val的
while (i <= n && nums[i] != val) {i++;}
// drd notes: 从后往前,找到首个 不等于val的
while (n >= i && nums[n] == val) {n--;}
if (i < n) {
nums[i++] = nums[n--];
} else {
return i;
}
}
return i;
}
}