Problem:
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].
分析:
有序数组去重。同样是两指针问题,一个指针负责遍历,另一个负责指向当前不重复数组的末端。
注意:STL中set可用来处理不重复问题,但也要注意滥用STL速度会下降。
AC Code(C++):
class Solution {
public:
//161 / 161 test cases passed.
//Runtime: 33 ms
int removeDuplicates(int A[], int n) {
if (A == NULL || n < 1) {//无效情况
return 0;
}
int index = 0;//指向不重复数组的最后一个元素
for (int i = 1; i < n; ++i) {//遍历
if (A[index] != A[i]) {
A[++index] = A[i];
}
}
return index + 1;
}
};