First Missing Positives

看了一下博客才有的思路,基本上来讲就是环状链表的思维,如果nums[i]不等于i + 1,即没有和下标对应上,则需要先找到这个值应该在什么位置,如果nums[i]不在 (0, n]的范围里面或者nums[i] == nums[nums[i] - 1]则忽略,如果满足条件则交换这两个数而且i不能动,另外这里要注意Python里面的交换值语法不能用来做同数组这种嵌套了元素值的交换,只能使用原始交换的方法

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        start = 0

        while start < n:
            if nums[start] != start + 1 and 0 < nums[start] <= n:
                if nums[start] != nums[nums[start] - 1]:
                    tmp = nums[nums[start] - 1]
                    nums[nums[start] - 1] = nums[start]
                    nums[start] = tmp
                    continue
            start += 1

        for i in xrange(n):
            if nums[i] != i + 1:
                return i + 1

        return n + 1

results matching ""

    No results matching ""