LeetCode Remove Duplicates from Sorted Array II
来源:互联网 发布:阿里算法平台 编辑:程序博客网 时间:2024/06/11 18:46
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 ofnums being 1
, 1
, 2
, 2
and3
. It doesn't matter what you leave beyond the new length.
题意:给出一有序数组,处理后使得重复的元素不能超过2个,并且返回数组的元素个数
思路:
算法步骤如下
1、如果当前元素与前一个元素相等,并且重复的个数没有超过2,就将当前元素存入数组,并且将重复记数加1
2、如果当前元素与前一个不相等,就将当前元素存入数组,重复记数置为1
代码如下
class Solution{ public int removeDuplicates(int[] nums) { int len = nums.length; int pos = 1; int cnt = 1; int ret = len > 0 ? 1 : 0; for (int i = 1; i < len; i++) { int cur = i; while (cur < len && nums[cur] == nums[cur - 1]) { if (cnt < 2) { nums[pos++] = nums[cur]; ret++; } cnt++; cur++; } if (cur < len) { nums[pos++] = nums[cur]; cnt = 1; ret++; } i = cur; } return ret; }}
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Leetcode Remove Duplicates from Sorted Array II
- 编程思想之多线程与多进程(3)——Java中的多线程
- [BZOJ2038]小Z的袜子
- 数据库还原和日志删除的SQL脚本
- HDU 2809God of War
- Linux 修改计算机名称
- LeetCode Remove Duplicates from Sorted Array II
- 《栀子花开》高清迅雷下载地址
- 多线程基础
- HTML文档基础
- Connection closed by 127.0.0.1
- 试试新功能
- 投影技术应用
- Android开发环境搭建
- Android 模拟Back键事件