Remove Duplicates from Sorted Array II解题报告

Description:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

Example:

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.

Link:

https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/

解题方法:

多加一个变量记录当前数字出现的次数,其余做法与Remove Duplicates from Sorted Array的做法一样

Time Complexity:

O(N)

完整代码:

int removeDuplicates(vector& nums) 
    {
        if(!nums.size())
            return 0;
        int time = 1, position = 1;
        for(int i = 1; i < nums.size(); i++)
        {
            if(nums[i] == nums[i - 1])
            {
                if(time < 2)
                {
                    nums[position] = nums[i];
                    position++;
                }
                time++;
            }
            else
            {
                time = 1;
                nums[position] = nums[i];
                position++;
            }
        }
        return position;
    }

你可能感兴趣的:(Remove Duplicates from Sorted Array II解题报告)