题目:
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]
.
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n <= 1) {
return n;
}
int cur = 0;
for(int i = 1; i < n; i++) {
if(A[cur] != A[i]) {
A[++cur] = A[i];
}
}
return cur + 1;
}
};
思路:
如果采用从前向后遍历、挪动是会超时的。本文代码假设有两个指针i与cur,i负责遍历数组,而cur经过的位置能够保证没有重复元素。