LeetCode 27 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.

代码

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        if (nums.begin() == nums.end()) return 0;
        vector<int>::iterator itor;
        for (itor = nums.begin(); itor + 1 != nums.end(); )
        {
            if (*(itor + 1) == val) {
                nums.erase(itor + 1);
            }
            else {
                itor++;
            }
        }
        itor = nums.begin();
        if (*itor == val) {
            nums.erase(itor);
            return nums.size();
        }
        return nums.size();
    }
};

你可能感兴趣的:(LeetCode 27 Remove Element(移除元素))