LeetCode | Remove Element

Remove Element

 Total Accepted: 56056 Total Submissions: 172938My Submissions

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.







思路:这一题考查点就是如何删除vector中的元素,问题在于删除符合条件的元素后,下一步该怎么做,注意:直接++p或者p++会出现运行时错误。

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        vector<int>::iterator p=nums.begin();
        int pp=nums.size();
        for(;p!=nums.end();)
        {
            if(*p==val)
              p=nums.erase(p);    //删除元素,返回值指向已删除元素的下一个位置
            else
              ++p;    //指向下一个位置
         }
        return nums.size();
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Tobyuyu/p/4965367.html