LeetCode上面有些题目的Follow up问题往往会限定一个苛刻的时间或空间复杂度。这些类型的题目如果不考虑Follow up要求的话,其实都比较容易求解。但是,为了满足Follow up的要求则必须使用一些tricky的方法,或者是一些比较特殊的算法。需要使用这类算法来解决的LeetCode问题是非常少的,因此,我把它们称之为小众算法。本文主要讨论两个这样的算法:Index sorting和Vote算法。注意,由于下面这些题目的Brute Force解法都非常直观,因此我们将直接考虑如何设计出满足Follow up要求的解法。
题目448:Find All Numbers Disappeared in an Array
Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
. Follow up: Could you do it without extra space and in O(n)
runtime? You may assume the returned list does not count as extra space.
通常来说,对数组中元素进行排序的时间复杂度是