Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
給定一個數組和一個target,返回數組中不等于target的元素個數,并將不等于target的元素移動到數組的前面。
public class Solution {
public int removeElement(int[] nums, int val) {
int length = 0;
int end = nums.length - 1;
int i = 0;
while (i <= end) {
if (nums[i] == val) {
while (end > i && nums[end] == val) end--;
if (end == i) break;
nums[i] = nums[end];
nums[end] = val;
} else {
length++;
i++;
}
}
return length;
}
}