描述
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.Your algorithm should run in O(n) time and uses constant space.
分析
使用基排序的技巧,将对应数字交换到它对应的下标上去。注意如果被交换来的数字依然不是他应该在的位置,应该持续交换。最多需要交换n
次。
要注意负数,越界数(大于数组长度的数)以及重复出现的数。
代码
Python
1 | class Solution(object): |