First Missing Positive

问题:给定一个无序数组,输出其中不存在的最小正整数

示例:

输入:[1,3,4]

输出:2

输入:[2,-1,1,4,5,4]

输出:3

输入:[6,5,4,7,8]

输出:1

解决思路:遍历数组中的元素i,如果为正整数且不大于数组的长度,则将其调整到 i - 1的位置处。之后,对调整后的数组进行遍历,如果该位置的元素不等于位置数加1,则返回位置数加1

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        for i in range(length):
            while length >= nums[i] > 0 and nums[i] != i+1 and nums[i] != nums[nums[i]-1]:
                nums[nums[i]-1],nums[i] = nums[i],nums[nums[i]-1]
        for i in range(length):
            if nums[i] != i + 1:
                return i + 1
        return length+1

 

posted @ 2019-05-07 12:54  秦qin  阅读(79)  评论(0编辑  收藏  举报