080 Remove Duplicates from Sorted Array II [Leetcode]
2015-08-02 12:56
453 查看
题目内容
Follow up for “Remove Duplicates”: What if duplicates are allowed at most twice?For example, Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
题目比较简单,用一个计数器和一个前向记录来判断是否删除下一个节点即可。注意erase会修改vector的长度。
运行时间20ms,代码如下:
class Solution { public: int removeDuplicates(vector<int>& nums) { if(nums.size() <= 2) { return nums.size(); } int pre(nums[0]), count(0), result(1); for(int i = 1; i < nums.size(); ++i) { if(nums[i] != pre) { count = 0; ++result; pre = nums[i]; } else { if(count == 0) { ++count; ++result; } else { nums.erase(nums.begin() + i); --i; } } } return result; } };
相关文章推荐
- [算法运用研究]图层混合
- 【转】UITableView使用详解
- php-面向对象(5)
- php-面向对象(4)
- 构造 Codeforces Round #275 (Div. 2) C. Diverse Permutation
- 增加swap空间
- 笔试题4
- HTML5
- 图论浅析--最短路之Dijkstra
- ubuntu14.04 系统负载监控器
- Java实现模拟路由功能
- Web Service学习-CXF开发Web Service实例demo(一)
- 图论浅析--最短路之Dijkstra
- GTK+编程入门(2)—GTK+程序结构
- 洛谷1373 小a和uim之大逃离
- [项目实战派]opencv通过dll调用matlab函数,图片作为参数
- CentOS使用EPEL YUM源
- [项目实战派]csharp通过dll调用opencv函数,图片作为参数
- teamfoundationserver2010之使用vs2010&&vs2013创建修改签入签出提交代码等操作
- thinkPHP隐藏url地址栏中的index.php方法