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

C++:
01 class Solution {
02 public:
03     int removeDuplicates(int A[], int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         if(n==0)
07             return 0;
08         int p=0;
09         int count=0;
10         int prv=A[0]1;
11         for(int i=0;i<n;i++)
12         {
13             if(A[i]!=prv)
14             {
15                 prv=A[p++]=A[i];
16                 count=1;
17             }
18             else if(count==1)
19             {
20                 A[p++]=A[i];
21                 count=2;
22             }
23         }
24         return p;
25     }
26 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s