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 int removeDuplicates(int A[], int n)
02 {
03     if(n==0)
04         return 0;
05     int j=0;
06     int data=A[0]1;
07     int cnt=0;
08     for(int i=0;i<n;i++){
09         if(A[i]!=data){
10            cnt=1;
11            data=A[j++]=A[i];
12         }else if(cnt<2){
13            cnt++;
14            A[j++]=data;
15         }
16     }
17     return j;
18 }
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