[Leetcode] Remove duplicates from sorted array 从已排序的数组中删除重复元素

时间:2022-03-03 09:41:02

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].

题意:除去重复的元素,若有重复只保留一个,返回长度。

思路:遍历数组,用不同的,覆盖相同的。过程:保存第一个元素的下标lo。遇到相等不管,继续遍历,遇到不等的,则将该值赋给lo的下一个,反复这样。代码如下:

 class Solution
{
public:
int removeDuplicates(int A[],int n)
{
if(n<=) return ;
int lo=;
for(int i=;i<=n-;++i)
{
if(A[lo] !=A[i])
A[++lo]=A[i];
}
return lo+;
}
};

思路相同,另一种写法:

 class Solution {
public:
int removeDuplicates(int A[], int n)
{
if(n<) return n;
int count=;
int flag=;
for(int i=;i<n;++i)
{
if(A[flag] !=A[i])
{
A[++flag]=A[i];
count++;
}
}
return count;
}
};