[leetcode]First Missing Positive @ Python


原題地址:https://oj.leetcode.com/problems/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.

解題思路:要求時間復雜度為O(n)和常數空間。又是一個tricky的解法。

class Solution:
    # @param A, a list of integers
    # @return an integer
    # @a very subtle solution
    def firstMissingPositive(self, A):
        n=len(A)
        for i in range(n):
            if A[i]<=0: A[i]=n+2
        for i in range(n):
            if abs(A[i])<=n:
                curr=abs(A[i])-1
                A[curr]=-abs(A[curr])
        for i in range(n):
            if A[i]>0: return i+1
        return n+1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM