Remove Element
2015-09-18 13:55
344 查看
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.
solution: use two pointer, start and end pointer, exchange the found value in start with value in end.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
solution: use two pointer, start and end pointer, exchange the found value in start with value in end.
class Solution { public: int removeElement(vector<int>& nums, int val) { if(nums.size() == 0) return 0; int start = 0; int end = nums.size()-1; while(start <= end) { while(end >= 0 && nums[end] == val) end--; if(end <= start) return end + 1; while(start < nums.size() && nums[start] != val) start++; if(end <= start) return start; if(nums[start] == val){ //swap. int tmp = nums[start]; nums[start] = nums[end]; nums[end] = tmp; start++; end--; } } return start; } };
相关文章推荐
- android ui分析 - 今日头条UI主界面
- uval1297 Palindrome 后缀数组求最长回文字串,lcp,rmq
- JS判断移动设备的终端类型(浏览器UserAgent)
- Java基础の乱弹琴二:break关键字
- 时间序列分析
- Hibernate – fetching strategies examples
- js函数参数设置默认值的一种变通实现方法
- 快排,动态内存
- git上传完整实例
- Android Studio插件给你带来开发便利
- Ubuntu 14.04 Storm(单机版)安装
- 手机淘宝中的那些Web技术-使用了类似PhoneGap的实现
- sessionID和cookie
- uva 400
- PHP学习笔记一
- android5.0开发之解决灭屏来日程只有声音没有亮屏
- c语言中 ++i 和 i++ 问题!
- The Castle(USACO 2.1.1)
- 一道面试题Lintcode196-Find the Missing Number
- 百度翻译API请求