Remove Duplicates from Sorted Array
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].
算法思想:
数组循环前移会超时,所以利用一辅助数组B去除不需要的元素,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n==0)return 0;
vector<bool> B(n,false);
for(int i=1;i<n;i++)
if(A[i]==A[i-1])
B[i]=true;
int count=0;
for(int i=0;i<n;i++){
if(!B[i])A[count++]=A[i];
}
return count;
}
};answer2
时间复杂度O(n),,空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
if(n==0)return 0;
int cnt=0;
for(int i=0;i<n;i++)
if(A[cnt]!=A[i])
A[++cnt]=A[i];
return cnt+1;
}
};
时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
return distance(A,unique(A,A+n));
}
};
answer4
时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(int A[], int n) {
int *first=A,*last=A+n,*cur=A;
while(first!=last){
*cur++=*first;
first=upper_bound(first,last,*first);
}
return cur-A;
}
};
删除排序数组中的重复项
本文介绍了一种在不使用额外空间的情况下从已排序数组中删除重复元素的方法。提供了三种解决方案,时间复杂度均为O(n),但空间复杂度分别从O(n)优化到了O(1)。这些算法通过迭代数组并仅保留唯一的元素来实现目标。
708

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



