面试编程题拾遗(03) --- 删除有序数组中的重复元素

题目:有一个已经排好序的数组,其中存在重复元素,请将重复元素删除掉,例如,A = [1, 1, 2, 2, 3],处理之后的数组应当为A = [1, 2, 3]。

 1 import java.util.Arrays;  
 2   
 3 public class Test03 {  
 4   
 5     public static int[] removeDuplicates(int a[]) {  
 6         if(a.length <= 1) {  
 7             return a;  
 8         }  
 9         int index = 0;  
10         for(int i = 1; i < a.length; i++) {  
11             if(a[index] != a[i]) {  
12                 a[++index] = a[i];  
13             }  
14         }  
15         int[] b = new int[index + 1];  
16         System.arraycopy(a, 0, b, 0, b.length);  
17         return b;  
18     }  
19       
20     public static void main(String[] args) {  
21         int[] a = {1, 1, 2, 2, 3};  
22         a = removeDuplicates(a);  
23         System.out.println(Arrays.toString(a));  
24     }  
25 }  
View Code

该算法的时间复杂度是O(n),空间复杂度为O(1)。

posted @ 2017-09-19 10:06  成那个林  阅读(387)  评论(0编辑  收藏  举报