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.
public int removeDuplicates(int[] A) {
int n = A.length;
if (n < 2)
return n;
int current = 0; // Index of the last "effective" number
for (int i = 1; i < n; i++) {
// When a different number is encountered,
// copy its value to the one at the next effective index
if (A[i] != A[i-1])
A[++current] = A[i];
}
return current+1;
}
Read full article from LeetCode - Remove Duplicates from Sorted Array | Darren's Blog
No comments:
Post a Comment