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用來遍歷數(shù)組,j用來記錄下一個可以放置元素的位置,整體思路是遍歷數(shù)組,如果元素不等于目標val,則保留,將其放在下一個可以放置元素的位置。如果相等則不做任何動作(這樣j指針就沒有更新,一直指向等于val的那個元素,則下次出現(xiàn)不等于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
}
}