80. Remove Duplicates from Sorted Array II
2016-04-13 17:56
267 查看
Remove Duplicates from Sorted Array II
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,
2and
3. It doesn’t matter what you leave beyond the new length.
本题和Remove Duplicates from Sorted List差不多,只需要增加一个标志位,来判断数字是否出现了两次即可。传入的参数从链表变成了数组,程序逻辑基本不变。
Code
public class Solution { public int removeDuplicates(int[] nums) { if (nums.length <= 2) { return nums.length; } int length = 1; int count = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) { if (count < 2) { nums[length++] = nums[i]; } count++; } else { count = 1; nums[length++] = nums[i]; } } return length; } }
相关文章推荐
- DeepLearning 知识点整理
- 盒子模型
- 使用SSL验证和Nginx做代理搭建生产环境的Docker仓库
- 计算内存大小与清除缓存文件
- 团队计划会议 01
- 循环创建按钮
- 【qt小贴士】Qt窗口置顶相关
- HBase数据迁移(3)-自己编写MapReduce Job导入数据
- 经典的Paxos算法
- Docker入门--简单使用--RHEL7.2
- RabbitMQ安装
- 【原创】k8s源码分析-----kubelet(8)pod管理
- haproxy 超时自动重发
- 个人知识点总结——Java并发
- 浏览器全屏
- 访问元素的尺寸和坐标
- haproxy 超时自动重发
- haproxy 超时自动重发
- 图片BlendMode 样式
- Java代码优化-在某种情况下避免Map的containsKey方法的使用