Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

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

 

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(n<=0)return 0;
 5         if(n==1)return n;
 6         int index=0;
 7         for(int i=1;i<n;i++)
 8         {
 9             if(A[i]!=A[index])
10             {
11                 index++;
12                 A[index]=A[i];
13             }
14         }
15         return index+1;//return index+1
16     }
17 };

 

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

 

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(n<3)return n;
 5         int index=1;
 6         for(int i=2;i<n;i++)
 7         {
 8             if(A[i]!=A[index]||(A[i]==A[index]&&A[i]!=A[index-1]))
 9             {
10                 A[index+1]=A[i];
11                 index++;
12             }
13         }
14         return index+1;
15     }
16 };

 

posted @ 2014-07-04 03:45  Hicandyman  阅读(147)  评论(0)    收藏  举报