Remove Duplicates from Sorted Array

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 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3         if(A.length == 0)
 4             return A.length;
 5         int B[] = new int[A.length];
 6         int k = 1;
 7         B[0] = A[0];
 8         for(int i = 1; i< A.length; i++){
 9             if(A[i] != B[k - 1]){
10                 B[k++] = A[i];
11             }
12         }
13         System.arraycopy(B, 0, A, 0, k);
14         
15         return k;
16     }
17 }

 

posted on 2014-11-11 11:11  luckygxf  阅读(129)  评论(0编辑  收藏  举报

导航