搜索此博客

2012年10月25日星期四

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].
01 public int removeDuplicates(int[] A) {
02     if(A.length<=1)
03         return A.length;
04     //current value    
05     int curr=A[0];
06   
07     //current index;
08     int i=1;
09   
10     //index without duplicates
11     int index=1;
12     int length=A.length;
13     while(i<A.length)
14     {
15         while(i<A.length && A[i]==curr)
16         {
17             i++;
18             length--;
19         }
20       
21         //replace duplicates
22         if(i<A.length)
23         {
24             A[index]=A[i];
25             curr=A[i];
26             i++;
27             index++;
28         }
29     }
30     return length;
31 }

没有评论:

发表评论