码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode First Missing Positive

时间:2017-08-17 14:25:31      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:while   not   ade   nes   title   时间复杂度   dcl   post   data   

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) 来获得相关源代码。

LeetCode First Missing Positive

标签:while   not   ade   nes   title   时间复杂度   dcl   post   data   

原文地址:http://www.cnblogs.com/zhchoutai/p/7381006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!