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