Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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].
题解:
双指针思想。并且保存前面遍历的元素的值。用以判断是否将新遍历的元素加入到数组中。
Code:
class Solution {
public:
int removeDuplicates(int A[], int n)
{
int preElement=0;
int pCur=0;
for(int i=0;i<n;i++)
{
if(i==0)
{
preElement=A[i];
A[pCur++]=A[i];
}
else
{
if(preElement!=A[i])
{
A[pCur++]=A[i];
preElement=A[i];
}
}
}
return pCur;
}
};
本文介绍了一种使用双指针技巧去除有序数组中重复元素的方法,并提供了代码实现。通过遍历数组,仅保留每个元素首次出现的实例,从而达到去重的目的。
1081

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



