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.

首先标记初始位置flag,然后统计与val相同的个数,之后删除相同元素即可。时间4ms,代码如下:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        if (nums.empty())
            return 0;
        sort(nums.begin(), nums.end());
        int n = nums.size(), len=n;
        int flag = -1;
        for (int i = 0, j = 0; i < n; i++){
            if (nums[i] == val){
                len--;
                if (flag==-1)
                    flag = i;
            }
        }
        if (len != n)
        for (size_t i = 0; i < n - len;++i)
            nums.erase(nums.begin() + flag);
        return len;
    }
};

 

posted on 2015-06-11 22:27  NealCaffrey989  阅读(131)  评论(0编辑  收藏  举报