Given a sorted array nums, 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 1:
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 returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],Your function should return length = 5, with the first five elements o
nums being modified to 0,1,2,3 and 4 respectively.
It doesn't matter what values are set beyond the returned length.
时间原因,题目就不解释了,然后说下我的思路。
这个想法和快速排序差不多,就是用两个指针去依次遍历数组,i从0开始,j从1开始,然后开始遍历,当发现下标i和j的元素相等时,就让j继续走下去,因为此时i和j指向的元素是相同的,接下来如果i和j指向的元素不相等,那就让i先向下走一步,保证i的值不会被覆盖,然后将j指向的元素赋值给i指向的元素,然后继续重复以上步骤。
代码如下:
class Solution: def removeDuplicates(self, nums): print(nums) i = 0 j = 1 while j<=len(nums)-1: if nums[i] == nums[j]: j += 1 continue else: i += 1 nums[i] = nums[j] j += 1 continue print(i+1) return nums[:i+1]
最终运行结果如下:
谢谢!