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.
题意:给出一有序数组,处理后使得重复的元素不能超过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;
}
}