LeetCode 之 Remove Element — C/C++实现

来源:互联网 发布:数控车螺纹编程实例 编辑:程序博客网 时间:2024/06/07 10:26

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.

给定一个数组和一个值,删除数组中所有和它相等的值,返回删除后新数组的长度。

数组元素的顺序可以改变。

分析:

法1:( C++ ) 顺序查找,利用 vector 的 erase 方法删除找到的元素,但是每次循环需要获取新的数组长度。


class Solution {public:    int removeElement(vector<int>& nums, int val) {       int numSize = nums.size();       vector<int>::iterator it = nums.begin();              for(int i = 0; i < numSize;)       {           if(nums[i] == val)           {               nums.erase(it + i);               numSize = nums.size();//删除元素后重新获取数组大小           }           else           {               ++i;           }       }              return nums.size();    }};

法2:( C语言 ) 顺序查找,找到相同的值后用数组末端的不等于val的值替换,可避免删除元素后数组元素的移动

int removeElement(int* nums, int numsSize, int val) {    int index = 0, end = numsSize-1;        if(!nums)/*空指针*/    {        return 0;    }    /*从头开始顺查找,找到等于val的值,用数组末端不等于val的值替换*/    while(index <= end)    {        if(nums[index] == val)        {            if(nums[end] != val)/*找到相等值,用末尾不相等值替换*/            {                nums[index++] = nums[end--];            }            else/*末尾值相等,找到不等于val的值*/            {                --end;            }        }        else        {            ++index;        }    }        return index;}


0 0