1. 程式人生 > >[Leetcode] Remove Duplicates from Sorted Array II

[Leetcode] Remove Duplicates from Sorted Array II

ref times 重復 leetcode 但是 cnblogs esc pro most

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