[Leetcode] Remove Duplicates from Sorted Array II

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Remove Duplicates from Sorted Array II相关的知识,希望对你有一定的参考价值。

Remove Duplicates from Sorted Array II 题解

题目来源:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/


Description

Follow up for "Remove Duplicates":

What if duplicates are allowed at most twice?

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.

Solution


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty())
            return 0;
        int size = nums.size();
        int id = 1;
        int dupTimes = 0;
        for (int i = 1; i < size; i++) {
            if (nums[i] != nums[i - 1]) {
                nums[id++] = nums[i];
                dupTimes = 0;
            } else {
                ++dupTimes;
                if (dupTimes < 2)
                    nums[id++] = nums[i];
            }
        }
        return id;
    }
};


解题描述

这道题题意是第一版的进阶:对已经排序的数组进行原地去重(即不使用额外空间),但是允许重复元素最多出现2次。这里的解法跟第一版基本相同,只是多用了一个计数器dupTimes,每次有重复元素就计数,没有重复元素就归零,重复不超过2次就与不重复视为一样。

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

LeetCode Remove Element

Leetcode.27 | Remove Element(Python)

LeetCode 546. Remove Boxes

leetcode 27 Remove Element

[Leetcode] 27 Remove Element

LeetCode OJ 27. Remove Element