Day2 Remove Duplicates from Sorted Array

LeetCode26:Remove Duplicates from Sorted Array


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

菜鸡思路是这样的:要求是不能使用额外空间。先将长度设置为数组的长度,遍历整个数组,如果发现某个数字的后面有重复的数字的话,就将当前数字设置为极小,同时长度减去1. 最后再来一次遍历,从后向前,将所有值为极小的数用后面的值覆盖掉,这样的话,数组前有效长度的位置就是不重复的数字,且保持了原来的相对顺序。


Day2 Remove Duplicates from Sorted Array


但是这样做呢实在是慢得要死,花了827ms。

修改思路:在discuss中学习了大佬的解法,代码十分精炼。与上述思路不同的是,这里记录的是重复数字的数目,从头到尾遍历一遍,当遇到重复数字时,记录加一,如果遇到的数字与前面的数字并不重复时,就将这个数字往前移动,覆盖掉重复的数字,这样一来,放在数组前面的自然就是不重复的数字了。


Day2 Remove Duplicates from Sorted Array


这样做的速度非常快,二十几毫秒就过了,也充分利用了所给是有序数组这一条件,因为如果是有序数组的话,重复的数字必然是相邻的,这样的话这种解法才是有效的。第一种虽然又蠢又慢,也可以适用于无序数组。