20170611-leetcode-041-First Missing Positive

1.Description

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.
解讀
給定一個無序的數組,找到第一個缺失的正整數,要求時間爲 O ( n )
比如:【1,2,0】,返回3
【900,-1】,返回1

2.Solution

思路:找到最大值,然後遍歷一下

class Solution(object):
    def firstMissingPositive(self, nums):
        if not nums: return 1
        maxNum = max(nums)
        for i in range(1, maxNum + 2):
            if i not in nums:
                return i
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章