【LeetCode】27. Remove Element
2016-03-08 10:26
162 查看
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排序,用迭代器遍历,当出现指定元素时就删除。
Runtime: 4
ms
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
class Solution { public: int removeElement(vector<int>& nums, int val) { if(nums.size() == 0) return 0; int len = nums.size(); int count = 0; for(int i =0; i < len; i++) { if(nums[i]!=val) { nums[count] = nums[i]; count++; } } return count; } };
二刷:先将vector排序,用迭代器遍历,当出现指定元素时就删除。
Runtime: 4
ms
class Solution { public: int removeElement(vector<int>& nums, int val) { int len = nums.size(); if(len==0) return 0; sort(nums.begin(),nums.end()); int count = 0; for(vector<int>::iterator it= nums.begin(); it != nums.end(); it++) { if((*it)==val) { nums.erase(it); it--; count++; } } return len - count; } };
相关文章推荐
- SolrCloud简介——solr 名词解释
- Unable to execute dex: Multiple dex files define
- VTK从TXT文件中读取数据
- Windows Azure Storage Client Library 2.0 入门
- Ubuntu下git使用
- SVN源代码管理规范
- ln函数详解
- iOS 边框显示不完全
- 计算机网络——6.局域网交换技术
- UIWebView打不开网页
- 大型网站架构系列:负载均衡详解
- 安卓和Java的垃圾回收
- MyEclipse中导入jdk源码
- Leetcode:118. Pascal's Triangle(JAVA)
- C++和C#进程之间通过命名管道通信(附源码)—下
- bootstrap弹出框无法调用问题解决
- javascript 闭包的特性
- KVC and KVO KVB
- ios富文本的简单使用 AttributedString
- activiti任务TASK