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.
思路:遍历数组,后边往前放。
public class Solution {
public int removeElement(int[] nums, int val) {
int newIndex = 0;
for (int oldIndex = 0; oldIndex < nums.length; ++oldIndex) {
if (nums[oldIndex] != val) {
nums[newIndex++] = nums[oldIndex];
}
}
return newIndex;
}
}