LeetCode 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.


Two pointers problem.

#include <iostream>
#include <vector>
using namespace std;

// duplicates are allowed at most twice.
int removeDuplicates(vector<int>& nums) {
    if(nums.size() <= 2) return nums.size();
    int i = 0;
    int count = 1;
    int j = 1;
    while(j < nums.size()) {
        if((nums[j] == nums[i]) && count < 2) {
            count++;
            nums[++i] = nums[j++];
        } else if(nums[i] != nums[j]) {
            nums[++i] = nums[j++];
            count = 1;
        } else {
            j++;
        }
    }
    return i + 1;
}                   // O(n) time complexity.

int main(void) {
    vector<int> nums{1, 1, 1, 1};
    int len = removeDuplicates(nums);
    cout << len << endl;
}


你可能感兴趣的:(LeetCode 80. Remove Duplicates from Sorted Array II)