Question
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]
.
Stats
Frequency | 3 |
Diffficulty | 1 |
Adjusted Difficulty | 1 |
Time to use | ---------- |
Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)
Analysis
This question is easy.
Solution
Two pointer operations. A very similar question is [LeetCode 27] Remove Element.
My code
public class Solution {
public int removeDuplicates(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int len = A.length;
int left = 0;
int right = 0;
while (right < len) {
A[left++] = A[right++];
// advance right pionter to a new value
while (right < len && A[right - 1] == A[right]) {
right++;
}
}
return left;
}
}