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 == 0) {
return 0;
}
int index = 0;
for (int i = 0; i < n; i++) {
if (A[index] != A[i]) {
index++;
A[index] = A[i];
}
}
return index+1;
}
};
本文介绍了一个高效的算法,用于在不使用额外空间的情况下移除已排序数组中的重复元素,并返回处理后数组的新长度。通过实例展示了如何仅利用常数级内存实现这一目标。
1106

被折叠的 条评论
为什么被折叠?



