Lintcode(7)-删除元素

来源:互联网 发布:一起装修网怎么样 知乎 编辑:程序博客网 时间:2024/05/22 00:54

Q:
Remove Element.
Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don’t matter.
Given an array [0,4,4,0,0,2,4,4], value=4
return 4 and front four elements of the array is [0,0,0,2]
A:
这个就是vector遍历删除的问题,可以直接用erase返回的迭代器,进行下一次访问。
这里我们不使用这种方式,直接使用std::remove,这个题目就是一行代码-:)。

class Solution {public:    /**      *@param A: A list of integers     *@param elem: An integer     *@return: The new length after remove     */    int removeElement(vector<int> &A, int elem) {        if (!A.size()) return 0;        A.erase(std::remove(A.begin(), A.end(), elem), A.end());        return A.size();    }};
0 0
原创粉丝点击