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]
.
注意是已经排好序的array, 再就是len 要+1。
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 }