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.
Solution:
看了提示说用two pointer,没有思路,参考discuss:
两个指针 i 和 j,其中i用来遍历数组,j用来记录下一个可以放置元素的位置,整体思路是遍历数组,如果元素不等于目标val,则保留,将其放在下一个可以放置元素的位置。如果相等则不做任何动作(这样j指针就没有更新,一直指向等于val的那个元素,则下次出现不等于val的元素时,那个元素就会被放在j指针指向的位置,与val相等的元素就被覆盖)
public class Solution
{
public int removeElement(int[] nums, int val)
{
int j = 0;
for(int i = 0; i < nums.length; i ++)
{
if(nums[i] != val)
{
nums[j] = nums[i];
j ++;
}
}
return j; // j get increased in the last iteration, so now its value is the length of the array
}
}