LeetCode-Python-448. 找到所有数组中消失的数字

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

思路:

线性扫描整个数组,用数组元素的值作为下标访问对应的元素,如果是第一次访问,就把对应元素转相反数。

最后再扫描一次整个数组,如果还有数组元素的值为正,就代表其下标对应的值没有在数组里出现过。

用abs(x)是为了保证下标一定为正,

用p - 1是为了把 1- n 映射到0 - n-1, 避免数组溢出。

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = list()
        
        for i, x in enumerate(nums):
            p = abs(x)
            if nums[p - 1] > 0:
                nums[p - 1] *= -1
        # print nums
        return [i + 1 for i, x in enumerate(nums) if x > 0]

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/88957886