[leetcode] 80. Remove Duplicates from Sorted Array II 解题报告

题目链接:https://leetcode.com/problems/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 1122 and 3. It doesn't matter what you leave beyond the new length.


思路:和上一个一样的,多了一个计数器而已,注意删除一个元素要用迭代器指针来删除。

代码如下:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        int old = nums[0], cnt = 1;
        vector<int>::iterator it = nums.begin()+1;
        while(it != nums.end())
        {
            if(*it == old)
            {
                if(cnt <2)
                { 
                    cnt++;
                    it++;
                }
                else
                    nums.erase(it);
            }
            else
            {
                old = *it;
                cnt = 1;
                it++;
            }
        }
        return nums.size();
    }
};


你可能感兴趣的:(LeetCode,算法,array)