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.
Analysis:
II和I没有太大区别,加个计数变量即可。
Source Code(C++):

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

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) {
            return 0;
        }
        if (nums.size() == 1){
            return 1;
        }
        int index=0;
        int count=1;
        for (int i=1; i<nums.size(); i++){
            if (nums.at(i)!=nums.at(index)){
                index++;
                nums.at(index)=nums.at(i);
                count=1;
            }
            else if (nums.at(i)==nums.at(index) && count<2)
            {
                count++;
                index++;
                nums.at(index)=nums.at(i);
            }
        }
        return index+1;
    }
};

int main() {
    vector<int> v;
    v.push_back(1);v.push_back(1);v.push_back(1);v.push_back(2);v.push_back(2);v.push_back(3);
    Solution sol;
    cout << sol.removeDuplicates(v) << endl;
    return 0;
}

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