LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素II)
2015-10-29 22:58
495 查看
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =
Your function should return length =
典型的双指针问题,维护两个指针不断更新就可以了,代码如下:
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,
2and
3. It doesn't matter what you leave beyond the new length.
典型的双指针问题,维护两个指针不断更新就可以了,代码如下:
class Solution { public: int removeDuplicates(vector<int>& nums) { int sz = nums.size(); if(!sz) return 0; int start = 0;//第二个指针 int i = 0;//第一个指针 int count = 0; int key = nums[0]; for(; i < sz; ++i){ if(nums[i] == key) count++; else{ for(int k = 0; k < min(2, count); ++k) nums[start++] = key;//更改数组元素,指针前移 key = nums[i]; count = 1; } } for(int k = 0; k < min(2, count); ++k) nums[start++] = key; return start; } };
相关文章推荐
- 宏定义
- 【ASC44E】【构造】Embedding Caterpillars 毛毛虫图向完全图的映射
- centos 6.x x86 源码安装git-2.3.0
- 程序员面试:电话面试问答Top 50
- 位域/字节对齐
- 创建销毁对象之遇到多个构造器参数时考虑用构建器(笔记)
- 我的第一个html
- 关于二叉堆(优先队列)的其他操作及其应用
- #ifdef endef的用法
- Scala学习笔记-环境搭建以及简单语法
- TreeSet类对象的比较
- 防sql注入解决方法
- python3 入门 (四) 类与继承
- [Django数据库模型]Django连接MySQL数据库的简单例子
- 流媒体加密(1)
- 项目冲刺-第二天
- 第七次作业——团队作业——项目冲刺———第二天
- 同步和互斥
- SQL Server中查询语句sql等SQL Server2008
- iOS开发之前言