leetcode[27]:Remove Element

来源:互联网 发布:局域网视频网站源码 编辑:程序博客网 时间:2024/06/03 01:41

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

更加简洁。

0 0
原创粉丝点击