10-2

41. 缺失的第一个正数

给定一个未排序的整数数组,找出其中没有出现的最小的正整数。

示例 1:

输入: [1,2,0]
输出: 3
示例 2:

输入: [3,4,-1,1]
输出: 2
示例 3:

输入: [7,8,9,11,12]
输出: 1
说明:

你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。

My solution:

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 1
        
        max_num = max(max(nums), 0)
        
        for i in xrange(1, max_num+2):
            if i not in nums:
                return i

分析:

(1)第一个 if 判断是为了避免输入的 nums 为空的情况;

(2)接下来,把 nums 中最大的数挑出来。这里要注意,nums中的数有可能全为负,因此这里要为得到的 max_num 设置一个下限。为了配合后面的程序,这里的下限设为0;

(3)for循环用于查找缺失的最小正整数;

(4)最坏情况下的时间复杂度:\(O(n)\),空间复杂度:\(O(1)\)

posted @ 2019-07-10 11:26  mingyu02  阅读(280)  评论(0)    收藏  举报