【题目】
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 nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
【题目分析】
这道题很重要的条件在于是一个已经排好序的数组,因此,这一点降低了难度。只需要记录需要删除的个数,用countVal记录,第一次出现的元素的最终位置就是它当前位置-countVal的值。这个题的思路和Remove Element 那道题很像。
【具体代码如下】
int removeDuplicates(int* nums, int numsSize) {
int countVal=0;
int i;
int newSize=numsSize;
for(i=0;i<numsSize-1;i++)
{
if(nums[i]==nums[1+i])
{
countVal++;
newSize--;
}
else
{
nums[i+1-countVal]=nums[i+1];
}
}
return newSize;
}
【个人总结】开始出错的地方是for循环语句中i的最终条件错误,对于numsSize个元素,只需要比较numsSize-1次就可以了,而i的初始值为0,所以应该是i