python第九周作业1:LeetCode First Missing Positive

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

难点:需要O(n)的时间复杂度且需要常数空间。

AC代码:

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        L=len(nums)
        for m in range(L):
            if nums[m]>L:
                continue
            val = nums[m]-1
            while nums[m]>0 and val<L and nums[val] != nums[m]:
                #小于等于0,大于等于长度的不换。
                nums[m],nums[val]=nums[val],nums[m]
                val = nums[m]-1
        for m in range(len(nums)):
            if nums[m] != m +1:
                return m +1
        return L+1

猜你喜欢

转载自blog.csdn.net/weixin_38742280/article/details/80212248