Leetcode 26 的题解
题目如下:
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.
最直接的做法是(如果能忽略掉不允许额外空间的题目要求的话)将每个独一无二的元素放入新数组中,然后将这些元素放回:
1 | int removeDuplicates(int* nums, int numsSize) { |
虽然这是个时间$O(n)$的算法,但我们同时也用了$O(n)$的空间。能不能不使用额外空间?
考虑到独一无二的元素个数总是不多于总元素个数,因此我们在nums
里循环遍历的时候,把nums
的前半部分当做这里的unique
数组是可行的。修改如下:
1 | int removeDuplicates(int* nums, int numsSize) { |
于是,我们满足了题目的要求,未使用额外空间。