zoukankan      html  css  js  c++  java
  • 41. First Missing Positive

    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.

    把nums[index]交换换到nums[nums[index]-1],再遍历

    class Solution(object):
        def firstMissingPositive(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            r_num=1
            if nums==None or nums==[]:
                return r_num
            n=len(nums)    
            for index in range(n):
                while nums[index]>0 and nums[index]<=n and nums[index]!=nums[nums[index]-1]:
                    temp=nums[index]
                    nums[index]= nums[nums[index]-1]
                    nums[temp - 1]=temp
            for index in range(n):
                if index+1!=nums[index]:
                    return index+1
            return n+1 
  • 相关阅读:
    装饰器(一)
    函数内置方法
    递归
    函数(三)
    python常用模块
    python模块与包
    python内置函数
    python函数
    python文件处理
    函数编程
  • 原文地址:https://www.cnblogs.com/rocksolid/p/6278599.html
Copyright © 2011-2022 走看看