Remove Element--LeetCode

来源:互联网 发布:fifa online3数据库16 编辑:程序博客网 时间:2024/06/06 08:59

1.题目

Remove Element

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.

2.题意

移除数组中等于val的元素,并返回新数组的长度

3.分析

1)遍历数组,将不等于val的值放回原数组
注意此前已经++index;所以最后return index;即可,不需要return index + 1;
2)每找到一个等于val的元素,将数组末尾的数移到该位置
这样可以保证如果没有重复就没有写操作
3)借助STL也可以AC,但不推荐

4.代码

1)

class Solution {public:    int removeElement(vector<int>& nums, int val) {        if(nums.size() == 0)            return 0;        int index = 0;        for(int i = 0; i < nums.size(); ++i)        {            if(nums[i] != val)            {                nums[index] = nums[i];                ++index;            }        }        return index;    }};

2)

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int len = nums.size();        if(len == 0)            return 0;        for(int i = 0; i < len; ++i)        {            if(nums[i] == val)            {                --len;                nums[i] = nums[len];                --i;            }        }        return len;    }};

3)

class Solution {public:    int removeElement(vector<int>& nums, int val) {        if(nums.size() == 0)            return 0;        return distance(nums.begin(), remove(nums.begin(), nums.end(), val));    }};