27. Remove Element

来源:互联网 发布:电脑怎么识别不了网络 编辑:程序博客网 时间:2024/06/02 19:19

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.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.
方法一、使用vector自带的函数erase (不好的办法)

int removeElement(vector<int>& nums, int val)     {        int len = nums.size();        if(len<=0)        {            return len;        }        vector<int>::iterator it;        for(it = nums.begin(); it != nums.end(); )        {            //cout<<*it<<endl;            if(*it == val)//注意:erase函数返回的是删除元素的后一个位置,自动隐含加一的操作             {                nums.erase(it);            }            else            {                it++;            }        }        return nums.size();     // return 0;      }

方法二、简洁的办法

int removeElement(vector<int>& nums, int val) {        int count = 0;        for(int i = 0; i < nums.size(); i++)        {            if(nums[i] == val)                count++;            else                nums[i-count] = nums[i];        }        return nums.size() - count;    }
0 0