【leetcode】448. Find All Numbers Disappeared in an Array

题目如下:

解题思路:本题对时间复杂度和空间复杂度都有要求,特别是空间,所以不能用字典之类的来记录已经出现的值。这里可以采用值-下标映射的方法,即把所有元素移动到其值减1的对应的下标的位置上,移动完成后,下标和值不匹配的元素即为缺失的number。例如输入[4,3,2,7,8,2,3,1],

[4, 3, 2, 7, 8, 2, 3, 1] # 初始状态
[7, 3, 2, 4, 8, 2, 3, 1] #4和下标为4-1的元素互换
[3, 3, 2, 4, 8, 2, 7, 1] #7和下标为7-1的元素互换
[2, 3, 3, 4, 8, 2, 7, 1] #依次类推
[3, 2, 3, 4, 8, 2, 7, 1]
[3, 2, 3, 4, 8, 2, 7, 1]
[3, 2, 3, 4, 8, 2, 7, 1]
[3, 2, 3, 4, 8, 2, 7, 1]
[3, 2, 3, 4, 8, 2, 7, 1]
[3, 2, 3, 4, 1, 2, 7, 8]
[1, 2, 3, 4, 3, 2, 7, 8]
[1, 2, 3, 4, 3, 2, 7, 8]
[1, 2, 3, 4, 3, 2, 7, 8]
[1, 2, 3, 4, 3, 2, 7, 8]
[1, 2, 3, 4, 3, 2, 7, 8] #标红的元素和下标不匹配

代码如下:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        inx = 0
        while inx < len(nums):
            # [4,3,2,7,8,2,3,1]
            if nums[inx] != nums[nums[inx]-1]:
                #swap 4 and 7, to make val match inx
                src = nums[inx]  # 4
                desc = nums[nums[inx]-1] # 7
                nums[inx] = desc
                nums[src - 1] = src
            else:
                inx += 1
        res = []
        for i,v in enumerate(nums):
            if i + 1 != v:
                res.append(i+1)
        return res
原文地址:https://www.cnblogs.com/seyjs/p/9303717.html