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]
.
Solutions:
use two pointers(indices),
at first, head=0, next=0,
if there is a duplicate digit, next++;
or copy the A[next] to A[head+1], head++, next++.
public class Solution {
public int removeDuplicates(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
int n = A.length;
if(n==0){
return 0;
}
if(n==1){
return 1;
}
// must consider above two cases;
int head = 0;
int next = 0;
int newLength = 0;
while(next<n){
if(A[head] == A[next]){
next++;
}else{
A[head+1] = A[next];
head++;
next++;
}
}
return newLength = head+1;
}
}