leetcode_Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":

What if duplicates are allowed at most twice?



For example,

Given sorted array A = [1,1,1,2,2,3],



Your function should return length = 5, and A is now [1,1,2,2,3].

  

class Solution {

public:

    int removeDuplicates(int A[], int n) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

         if(n<2) return n;

        int value,count =1;

        value = A[0];

        int length = 0;

        for(int i = 1;i<n;i++)

        {

           if(A[i] == value){

                count++;

                if(count >2)

                   length++;

                 else if(length >0)

                    A[i-length] = A[i];                  

           }else{

           

                value = A[i];

                count = 1;

                if(length >0)

                  A[i-length] = A[i];    

           }

        }

        return n-length ;

    }

};

 

你可能感兴趣的:(LeetCode)