Description:
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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Thoughts:
首先我们需要两个计数指针,第一个指针pos它用来遍历数组,第二个指针length用来记录当前除去val元素后的长度。如果当前pos指针指向的值等于val,那么只把pos指针递增,否则说明当前的元素应该包含在新的数组中那么我们就把数组中length的位置的值赋值为pos指针所指向的值,然后将pos和length 的值都加1。
以下是我的java代码:
package easy.array; public class RemoveElement {
public int removeElement(int[] nums, int val) {
int length = 0;
int pos = 0;
while(pos < nums.length){
if(nums[pos] == val){
pos++;
}else{ nums[length] = nums[pos];
pos++;
length++;
}
}
return length;
}
public static void main(String[] args){
RemoveElement re = new RemoveElement();
int[] nums = {3,2,2,3};
int val = 3;
int returnnum = re.removeElement(nums, val);
System.out.println(returnnum);
}
}