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.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn’t matter what you leave beyond the returned length.
给一个数组和一个指定值val,让在数组中原地去掉(也就是替换掉指定的值val),返回长度,不需要考虑长度外的元素,而且可以不保留原有元素的顺序
思路:
双指针,一个指向要替换的位置,一个向前走到替换它的元素,即用val之外的值替换val
public int removeElement(int[] nums, int val) {
if(nums == null || nums.length == 0) {
return 0;
}
int index = -1;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != val) {
index ++;
//自己和自己交换,相当于不变
nums[index] = nums[i];
}
}
return (index + 1);
}