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         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(A == null || A.length == 0) return 0;
 5         if(A.length == 1) return 1;
 6         int start = 0;
 7         for(int i = 0; i < A.length; i ++){
 8             if(A[i] != A[start]){
 9                 A[++start] = A[i];
10             }
11         }
12         return ++start;
13     }
14 }

 

第三遍:

 1 public class Solution {
 2     public int removeDuplicates(int[] A) {
 3         if(A == null || A.length == 0) return 0;
 4         int len = 0;
 5         for(int i = 1; i < A.length; i ++){
 6             if(A[i] != A[len]){
 7                 len ++;
 8                 A[len] = A[i];
 9             }
10         }
11         return len + 1;
12     }
13 }

 

posted on 2014-08-07 08:46  Step-BY-Step  阅读(111)  评论(0编辑  收藏  举报

导航