leetcode: 41. First Missing Positive

来源:互联网 发布:ps怎么装磨皮软件 编辑:程序博客网 时间:2024/06/13 22:16

Q

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.

AC

class Solution(object):    def firstMissingPositive(self, nums):        """        :type nums: List[int]        :rtype: int        """        length = len(nums)        if len(nums) == 0:            return 1        lst = range(1, length+2)        for i in nums:            if i > 0 and i < length+1 and i in lst:                lst.remove(i)        return lst[0]class Solution2(object):    def firstMissingPositive(self, A):        i = 0        while i < len(A):            if A[i] > 0 and A[i] - 1 < len(A) and A[i] != A[A[i]-1]:                A[A[i]-1], A[i] = A[i], A[A[i]-1]            else:                i += 1        for i, integer in enumerate(A):            if integer != i + 1:                return i + 1        return len(A) + 1if __name__ == "__main__":    assert Solution().firstMissingPositive([1,2,0]) == 3    assert Solution().firstMissingPositive([3,4,-1,1]) == 2