LeetCode OJ 80. Remove Duplicates from Sorted Array II

Posted yunanlong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 80. 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 1, 1, 2, 2 and 3. It doesn‘t matter what you leave beyond the new length.

解答

这题又是一遍AC。。。只能说LeetCode上水题有点多,这居然都是Medium难度。。。

拿一个变量计数一下重复次数就可以了,每次遇到新的数就将这个变量赋值为1,如果这个变量达到2且遇到和之前重复的数,就移除。

下面是AC的代码:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0){
            return 0;
        }
        int last = nums[0];
        int count = 1;
        int dup = 1;
        for(vector<int>::iterator iter = nums.begin() + 1; iter != nums.end(); iter++){
            if(*iter == last){
                if(dup < 2){
                    dup++;
                    count++;
                }
                else{
                    nums.erase(iter);
                    iter--;
                }
            }
            else{
                dup = 1;
                count++;
                last = *iter;
            }
        }
        return count;
    }
};

118



以上是关于LeetCode OJ 80. Remove Duplicates from Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ_题解(python):027-Remove Element ArrayEasy

LeetCode OJ 203Remove Linked List Elements

LeetCode OJ 26. Remove Duplicates from Sorted Array

LeetCode OJ Remove Duplicates from Sorted Array II

LeetCode OJ 83. Remove Duplicates from Sorted List

LeetCode OJ 82. Remove Duplicates from Sorted List II