LeetCode Algorithms #27 <Remove Element>
2016-04-01 18:39
441 查看
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
思路:
先把所有的给定数值都挪到数组末端,然后再用erase删除掉这些元素。
解:
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
思路:
先把所有的给定数值都挪到数组末端,然后再用erase删除掉这些元素。
解:
class Solution { public: int removeElement(vector<int>& nums, int val) { if(!nums.size()) return 0; auto itFront = nums.begin(); auto itBack = --nums.end(); for(; itFront < itBack; itFront++) { if(*itFront == val) { while(*itBack == val && itBack > itFront) itBack--; *itFront = *itBack; *itBack = val; } } for(itFront = nums.begin(); *itFront != val && itFront != nums.end(); itFront++); if(itFront != nums.end()) nums.erase(itFront, nums.end()); return nums.size(); } };
相关文章推荐
- HDU 5642 King's Order
- just proxy 代理工具 上谷歌google 2016年最新
- 窗体透明,但窗体上的控件不透明(简单好用)good
- Codeforces 653B Bear and Compressing
- 【GOF23设计模式】_观察者模式
- django UnicodeEncodeError
- django cache 设置
- Google Gson 使用简介
- Zookeeper全解析——Paxos作为灵魂
- uva11090Going in Cycle!!(最短路spfa)
- Django 自带comment评论库使用
- tinyos-2.1.1目录结构解析
- Django Ajax CSRF 认证
- Go语言中的错误处理系统
- how to use google
- go简易udp客户端和服务器
- 【Google Code Jam】Problem A. Store Credit
- 使用ecgo框架编写demo
- POJ-3274 Gold Balanced Lineup
- Django框架使用