41 First Missing Positive Number

思路很奇妙,首先进行初始条件的处理,首先判断1是否在数组中,然后将数组中小于等于0的元素和大于数组长度的元素换成1。之后处理时候,按照num[i] 的数值对对应下标做反转符号操作,这样可以在in-place的空间通过值得符号记录是否存在等。

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = 1
        if ans not in nums:
            return ans
        if nums == [1]:
            return 2
        length = len(nums)
        for i in range(length):
            if nums[i] <= 0 or nums[i] > length:
                nums[i] = 1

        for i in range(length):
            a = abs(nums[i])
            if a == length:
                nums[0] = -abs(nums[0])
            else:
                nums[a] = -abs(nums[a])
        for i in range(1, length):
            if nums[i] > 0:
                return i
        if nums[0] > 0:
            return length
        return length + 1

results matching ""

    No results matching ""