LeetCode | 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.
思路:这一题考查点就是如何删除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(); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
posted on 2015-05-23 16:49 Tob__yuhong 阅读(135) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步