码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]First Missing Positive @ Python

时间:2014-06-09 17:44:43      阅读:980      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

原题地址: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的解法。

bubuko.com,布布扣
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
bubuko.com,布布扣

 

[leetcode]First Missing Positive @ Python,布布扣,bubuko.com

[leetcode]First Missing Positive @ Python

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3777496.html

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