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

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



