码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array

时间:2014-10-22 19:46:16      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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

 

 

way1:stupid....

but accepted....

 1  if(A.length==0)return 0;
 2         int i=0;int j=1;
 3         int temp=A[0];
 4         while(i<A.length)
 5         {
 6             while(A[i]==temp&&i<A.length)
 7             {
 8                 if(i==A.length-1)break;
 9                 i++;
10             }
11             if(i!=A.length-1)
12             {
13                 temp=A[i];
14                 A[j++]=A[i++];
15             }
16             else
17             {
18                 if(A[i]==temp)
19                 {
20                     j--;
21                     i++;
22                 }        
23                 else
24                     A[j]=A[i++];
25             }
26             
27         }
28         A=Arrays.copyOf(A, j+1);
29         return j+1;

 

 

2!:

 1                if(A.length==0)return 0;
 2                   int index=1;
 3         for(int i=1;i<A.length;i++)
 4         {
 5             if(A[i]!=A[i-1])
 6             A[index++]=A[i];
 7         }
 8         
 9         return index;
10                         

 

Remove Duplicates from Sorted Array

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/sweetculiji/p/4043835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!