Remove Element
2015-08-26 10:46
429 查看
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时,找到指定的位置后不能直接删除当前位置的it(vector::iterator it = nums.begin()),如果直接删了就无法链接到这个it之后的元素.代码如下”
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
思路:这道题难度不大,但是有个易错点,就是在使用迭代器遍历vector时,找到指定的位置后不能直接删除当前位置的it(vector::iterator it = nums.begin()),如果直接删了就无法链接到这个it之后的元素.代码如下”
class Solution { public: int removeElement(vector<int>& nums, int val) { if(nums.empty()) return 0; for(vector<int>::iterator it = nums.begin(); it != nums.end();){ if(*it == val){ it = nums.erase(it);//不能写成nums.erase(it); } else it++; } return nums.size(); } };
相关文章推荐
- HDU 4267 A Simple Problem with Integers(树状数组)
- poj 3164 Command Network 【最小树形图】【朱刘算法 入门】
- Spring MVC控制层redirect
- n!的长度(stirling公式的应用)
- C#中的IComparable 和 IComparer 接口,实现列表中的对象比较和排序
- 关于Reportviewer
- PAT (Basic Level) Practise:1019. 数字黑洞
- XML语言:可扩展的标记语言;
- Fiddler-005-获取 Cookie 信息
- Android调试
- Linux内核启动及文件系统加载过程
- 读jQuery源码之旅(1)
- json相关
- XMPP协议学习笔记一
- hdu 4135 Co-prime 容斥原理
- 【POJ1258】【最小生成树水题】
- JS中 Math方法
- ASP杂记
- 了解JavaScript(1)- Hello World
- linux-arm间tftp命令的安装、使用