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]
.
比較簡單的一個題, 時間O(n), 空間O(1)
public class Solution {
public int removeDuplicates(int[] A) {
// use two pointers
int len = A.length;
int p = 0, q = 0;
// p at where to be replaced and q at the scanning position
while( q < len){
int tmp = A[q];
while(q < len && A[q] == tmp) q++;
A[p++] = tmp;
}
return p;
}
}