**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.**
本题目比较容易,要求在一个给定的有序数组中去除重复的元素(例如如果一个元素有多个,则只留一个)
本题目的解法同样是数组问题的经典解法,双指针即可解决问题。
让我们来看一下代码:
int removeDuplicates(int* nums, int numsSize) {
int* numsl; /*双指针*/
if(numsSize==0) /*很重要,第一次没有发现,程序的完备性很重要*/
return 0;
int j=1;
numsl=nums;
for(int i=0;i<numsSize-1;i++) /*循环遍历给定数组*/
{
nums++;
if(*nums!=*numsl) /*发现不重复元素,存储*/
{
numsl++;
*numsl=*nums;
j++; /*记录新数组的元素个数*/
}
}
return j;
}