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
public class Solution { public int removeDuplicates(int[] A) { // Start typing your Java solution below // DO NOT write main() function if (A== null) return 0; int len = A.length ; if( len <= 1) return A.length; int index = 0; for(int i = 0 ; i < len ; i++){ if(A[i] == A[index]) {continue;} index++; A[index] = A[i]; } return index+1; } }
public class Solution { public int removeDuplicates(int[] A) { // Start typing your Java solution below // DO NOT write main() function if (A== null) return 0; int len = A.length ; if( len <= 1) return A.length; int i =0; while(i < len-1){ if(A[i] == A[i+1]){ for(int j = i ; j < len -1 ; j++){ A[j] = A[j+1]; } len--; } else{ i++; } } return len; } }
class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): if len(A) == 0: return 0 if len(A) == 1: return 1 index = 0 for i in A[1:]: if i != A[index]: index = index +1 A[index] = i return index+1