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.
思路:
變量i,j分別指向數組的首部和尾部,變量k存儲數組中有多少與val相同的元素。不斷循環將數組尾部的非val的數組元素賦值給數組首部的nums[i](nums[i] = val)。用k記錄數組中val的個數,返回numsSie - k。
代碼:
int removeElement(int* nums, int numsSize, int val) {
int i = 0, j = numsSize - 1, k = 0;
while(i <= j)
{
while(j >= i && nums[j] == val)
{
j--;
k++;
}
if(i <= j && nums[i] == val)
{
nums[i] = nums[j];
j--;
k++;
}
i++;
}
return numsSize - k;
}