leetcode41_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.

給定一組integers,找出其中最小的缺失的正整數值,要求時間複雜度爲O(n),空間複雜度爲O(1)。


二.代碼編寫

時間複雜度爲O(n)意味着不能直接對list進行排序O(NlogN),空間複雜度爲常數意味着不能新建一個list。

常數空間,我們應該想到直接swap,將相應得到數字m放到list的(m-1)的位置上。全部交換完畢後,返回list中第一個不滿足nums[m]!=m+1的(m+1)值。

代碼如下:

'''
@2016.11.20 by wttttt
@ for problem details, see https://leetcode.com/problems/first-missing-positive/
@ for solution description,see
@ trick
'''
class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if nums == []:
            return 1
        len_nums = len(nums)
        i = 0
        while i< len_nums:
            if nums[i]!=i+1 and nums[i]<=len_nums and nums[i]>0:
                #nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i]  # swap
                tmp = nums[i]
                if tmp == nums[tmp-1]:
                    i += 1
                    continue
                nums[i] = nums[tmp-1]
                nums[tmp-1]=tmp
            else:
                i += 1
        for i in range(len_nums):
            if nums[i] != i+1:
                return i+1
        return nums[-1]+1




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章