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 by modifying the input array in-place with O(1) extra memory.
Example:
Given 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.
int removeDuplicates(int* nums, int numsSize)
{
if(NULL == nums || numsSize <= 0)
return 0;
int j = 1;
for(int i = 1;i < numsSize;i++)
{
if(nums[i-1] == nums[i])
{
continue;
}
nums[j++] = nums[i];
}
return j;
}
方法二:
int removeDuplicates(int* nums, int numsSize)
{
if(NULL == nums || numsSize <= 0)
return 0;
int j = 0;
for(int i = 1;i < numsSize;i++)
{
if(nums[j] == nums[i])
{
continue;
}
nums[++j] = nums[i];
}
return j + 1;
}
经验与教训
在前面LeetCode 1&&27代码中并没有判断数组个数与是否为空也是可以通过的,但是这道题如果不对数组个数加以判断会提示空数组用例失败。
解题思路与LeetCode26一致,譬如一个数组为1,1,2,3,数组中保存的第一个元素肯定不用比较,所以下标从1开始比较,如果与前面nums[0]内从相同,则i++进入下一次循环,此时i = 2,nums[2]与nums[1]不同,因此把nums[2]赋值给nums[1],执行完该语句后j指向下一个需要赋值的下标。