LeetCode Problem
26. Remove Duplicates from Sorted Array
Link to LeetCode
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].
Analysis
The problem is pretty straightforward.
It returns the length of the array with unique elements, but the original array need to be changed also.
This problem is similar to Remove Duplicates from Sorted Array II.
public static int removeDuplicates(int[] A) {
if (A.length < 2)
return A.length;
int j = 0;
int i = 1;
while (i < A.length) {
if (A[i] != A[j]) {
j++;
A[j] = A[i];
}
i++;
}
return j + 1;
}
Note that we only care about the first unique part of the original array.
So it is ok if input array is {1, 2, 2, 3, 3}, the array is changed to {1, 2, 3, 3, 3}.