LeetCode(27)题解:Remove Element
2015-06-19 00:00
417 查看
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.
思路:
因为可以改变元素顺序,所以只需要把最后端的非val元素用最前端的val代替即可,前后两个指针同时移动直到相遇。
AC代码:
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.
思路:
因为可以改变元素顺序,所以只需要把最后端的非val元素用最前端的val代替即可,前后两个指针同时移动直到相遇。
AC代码:
class Solution { public: int removeElement(vector<int>& nums, int val) { int i=0,n=nums.size()-1; if(n<0) return 0; while(nums ==val) n--; if(n<0) return 0; while(i<n){ while(nums ==val){ n--; } if(i>n) break; if(nums[i]==val){ nums[i]=nums ; n--; } i++; } while(nums ==val){ n--; } return n+1; } };
相关文章推荐
- 大道至简_阅读笔记02
- net命令
- Thunderbird Mail 支持 Microsoft Exchange
- error: Error parsing XML: unbound prefix 解决办法
- Thunderbird Mail 支持 Microsoft Exchange
- 开发文档
- Linux/Ubuntu学习笔记(六)--tomcat
- 建立你自己的知识管理系统:学习、保存、分享!
- JS - 关于改变Javascript的作用域链
- 关于HTML5中Video标签无法播放mp4的解决办法
- Linux/Ubuntu学习笔记(六)--JDK安装及一个java例程
- ListView上拉加载更多(分页加载)
- leetcode刷题,总结,记录,备忘 226
- GO GO GO
- 【猫猫的Unity Shader之旅】之Lambert光照
- 使用jstl的Foreach 和jquery的each()的index属性
- .NET跨平台:在CentOS上编译dnx并运行ASP.NET 5示例程序
- Linux学习笔记(五)--SSH
- ECMAScript 作用域
- 在Windows系统上安装Ruby On Rails