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.
http://blog.csdn.net/linhuanmars/article/details/20023993
属于面试中比较简单的题目。做法是维护两个指针,一个保留当前有效元素的长度,一个从前往后扫,然后跳过那些重复的元素。因为数组是有序的,所以重复元素一定相邻,不需要额外记录。时间复杂度是O(n)
http://blog.csdn.net/linhuanmars/article/details/20023993
属于面试中比较简单的题目。做法是维护两个指针,一个保留当前有效元素的长度,一个从前往后扫,然后跳过那些重复的元素。因为数组是有序的,所以重复元素一定相邻,不需要额外记录。时间复杂度是O(n)
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