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;
}
本文介绍了一种在原地且使用常数级内存的方式去除数组中特定值的方法。通过双指针技巧,该算法能够有效地将指定值从数组中移除,并返回新的长度。文章详细解释了实现思路并提供了具体的C语言代码示例。
436

被折叠的 条评论
为什么被折叠?



