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;
}