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;
}
}