题目:
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.
不能使用其他的数组存储,必须在常数内存里完成,即空间复杂度为O(1)
For example,
Given input array A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
代码1:
class Solution {
public:
int removeDuplicates(int A[], int n)
{
if(n == 0)
return 0;
int new_len=0;
for(int i=1;i<n;i++)
{
//法一
while(A[i] == A[new_len] && i < n)//循环结束条件,遇到不相等的数,或者到达数组末尾
i++;
if(i < n) //如果还未到达末尾,则把不重复的数赋给A[new_len];
A[++new_len] = A[i];
//法二
//if (A[i] != A[new_len])
// A[++new_len] = A[i];
}
return new_len+1;//注意上面的new_len是下标,要返回的数是个数,因此要+1
}
};
代码2:
class Solution {
public:
int removeDuplicates(int A[], int n)
{
return distance(A, unique(A, A + n));//直接使STL
}
};
代码3:
class Solution {
public:
int removeDuplicates(int A[], int n)
{
if(n < 2 )
return n;
int result = 1;
for(int i = 1 ; i < n ; i++)
{
//if 执行完后result向后移动一个,之后A[i]和result之前的一位相比较
//如果和之前的相同,则i++,如果不同,则把A[i]赋给当前result,然后result再加1位
//这里的1代表只能出现一次,如果改为2,则意味着相同的数可以出现2次,改为n,意味着可以出现n次
if(A[i] != A[result - 1])
A[result++] = A[i];
}
return result;
}
};