• LeetCode First Missing Positive


    LeetCode解题之First Missing Positive


    原题

    找出一个无序数组中缺少的最小的正整数。

    注意点:

    • 时间复杂度为O(n)
    • 仅仅能使用常数级额外空间

    样例:

    输入: nums = [1, 2, 0]
    输出: 3

    输入: nums = [3,4,-1,1]
    输出: 2

    解题思路

    因为仅仅须要找出缺少的第一个正整数,我们最好还是把全部正数放到相应的位置。再找到第一个位置不匹配的地方原本应该放哪个数。

    如上面的样例[1,2,0]就已经排列好了,而[3,4,-1,1]应变为[1,-1,3,4]。分别遍历这两个数组,找到nums[i]!=i+1的位置,假设全部位置都符合,说明全部的数组成了从1開始的连续正整数。

    进行排列的方法就是依次遍历每一个数字,把它们放到应该放置的位子。

    AC源代码

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

    欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

  • 相关阅读:
    IfcFeatureElementAddition
    IfcOpeningElement
    IfcRelNests
    IfcElementAssemblyType
    IfcProjectionElement
    IfcFeatureElement
    IfcRelDefines
    Win10 Anaconda配置tensorflow
    Anaconda升级
    Anaconda 台式机环境
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7381006.html
Copyright © 2020-2023  润新知