[LeetCode] Remove Element 分析
2016-02-02 14:03
288 查看
Remove Element算是LeetCode的一道水题,不过这题也有多种做法,现就我所知的几种做一点讨论。
题目链接:https://leetcode.com/problems/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.
要注意的是“It doesn't matter what you leave beyond the new length.”
思路分析:思路很简单,直接上代码。
Solution 1:暴力移动
Solution 2:使用STL
关于Solution 2中STL的使用:
1,remove算法描述:查找的得到第一个元素的位置,然后从此位置开始遍历容器,将后面的元素依次前移,跳过和value相同值的元素,也就是说,所有和value相同值的元素都会被覆盖,而其他的元素都会依次前移。最后remove返回"指向最后一个'有用'元素的iterator",但是在remove算法过程中,并没有修改原容器的size,以及end()
2,distance()用于求出迭代器之间的距离,即两个参数之间的元素个数。
题目链接:https://leetcode.com/problems/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.
要注意的是“It doesn't matter what you leave beyond the new length.”
思路分析:思路很简单,直接上代码。
Solution 1:暴力移动
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val){ 4 int len = nums.size(); 5 int ptr = 0; 6 int newLen = 0; 7 for(int i = 0;i<len;i++) 8 { 9 if(nums[i]!=val) 10 { 11 nums[ptr++]=nums[i]; 12 } 13 } 14 newLen = ptr; 15 return newLen; 16 } 17 };
Solution 2:使用STL
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val) { 4 auto end = remove(nums.begin(),nums.end(),val);//这里用到了自动指针 5 return distance(nums.begin(),end); 6 } 7 };
关于Solution 2中STL的使用:
1,remove算法描述:查找的得到第一个元素的位置,然后从此位置开始遍历容器,将后面的元素依次前移,跳过和value相同值的元素,也就是说,所有和value相同值的元素都会被覆盖,而其他的元素都会依次前移。最后remove返回"指向最后一个'有用'元素的iterator",但是在remove算法过程中,并没有修改原容器的size,以及end()
2,distance()用于求出迭代器之间的距离,即两个参数之间的元素个数。
相关文章推荐
- 浅谈“be practical and realistic”
- VMware虚拟机安装了vmwaretools却不能共享主机文件夹
- Python Scrapy抓取数据
- 面对对象程序设计第二次作业
- jQuery UI 实例 - 拖动排序(Sortable)
- DB2 查看锁
- Spring通过构造方法注入的四种方式
- Mysql的row_format
- Redis 实例:主从复制
- 欧拉回路——骑马修栅栏
- brew 任何命令 都 报 synatx error
- [.net 面向对象程序设计进阶] (22) 团队开发利器(一)简单易用的代码管理工具VSS
- java web 过滤器跟拦截器的区别和使用
- 装饰模式(Decorator Pattern)
- tinyXML入门
- 方便的Chrome取色插件ColorPick Eyedropper [设计, FE必备]
- 移植mplayer到itop4412开发板
- Python 10.9 urllib
- 外贸人都必须知道的国际贸易壁垒
- Android WebView使用实例(html5、文件下载和远程URL)