您的位置:首页 > 其它

leetcode[27]:Remove Element

2015-06-16 21:08 267 查看
Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

int removeElement(int* nums, int numsSize, int val) {
int i;
int k=0;
for(i=0;i<numsSize;i++)
{
if(nums[i]==val)
{
k++;
nums[i]=nums[i + k];
i--;
}
else nums[i+1]=nums[i + k + 1];
if(i==numsSize-k-1) break;
}
return numsSize-k;
}


新长度之前的值要不存在val才行,所以需要变量替换,用游标实现。

也可以用双指针实现:

int removeElement(int* nums, int numsSize, int val) {
int i;
int k=0;
for(i=0;i<numsSize;i++)
{
if(nums[i] != val)
{
nums[k++]=nums[i];
}
}
return k;
}


更加简洁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  array