题目
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 i=0;
for(int j=1;j<n;j++)
{
if(A[j]!=A[j-1])
A[++i]=A[j];
}
return i+1;
}
};
本文介绍了一种方法,在不使用额外数组的情况下,移除一个已排序数组中的重复元素,并返回新的数组长度。代码示例中定义了一个名为Solution的类,包含一个名为removeDuplicates的方法,该方法接收一个整数数组A和其长度n作为参数,通过遍历数组并比较相邻元素来实现目标。
1094

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



