Lintcode(7)-删除元素

本文介绍了一种利用C++ STL中的std::remove函数高效移除数组中特定值的方法,并提供了一个简洁的实现示例。

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();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值