问题描述:
Given an array and a value, 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.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
分析:
和26题要求一样,都不能分配额外的空间出来。和26题的官方答案一个思路,由删除未知个数的重复元素变为删除一个重复元素。同样是两个指针,一个从0出发,存储非指定值,另一个也是从0出发,寻找与指定值不同的值赋给第一个指针。
代码如下:
public int removeElement(int[] nums, int val) {
if(nums.length == 0) return 0;
int i = 0;
for(int j=0; j<nums.length; j++){
if(nums[j] != val){
nums[i++] = nums[j];
}
}
return i;
}