您的位置:首页 > 其它

Remove Duplicates from Sorted Array--从有序数组中移除重复元素

2014-06-22 16:53 651 查看
问题:链接

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]
.
解答:
两个指针,first指向最后一个非重复元素,last指向未处理的元素的第一位,两个指针都初始化为0。

代码:

class Solution {
public:
int removeDuplicates(int A[], int n) {
int first,last;
first = last = 0;
if(n == 0)
return 0;
while(last != n)
{
if(A[first] == A[last])
{
++last;
}
else
{
A[first+1] = A[last++];
++first;
}
}
return first+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐