[LeetCode] 448. Find All Numbers Disappeared in an Array

原题

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.数组

Find all the elements of [1, n] inclusive that do not appear in this array.bash

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.app

Example:this

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]
复制代码

解答

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """ :type nums: List[int] :rtype: List[int] """
        for num in nums:
            index = abs(num) - 1
            nums[index] = -abs(nums[index])
        return [i + 1 for i, num in enumerate(nums) if num > 0]
复制代码

使用一个 dict 解决固然很是容易,相对比较难的是完成题目中的「without extra space and in O(n) runtime」。spa

上面这种解决方案,是将数字和 index 巧妙的作了对应:code

将数组中数字看做下标,而后对应这个“下标”去修改数组中元素的符号;循环一圈后,看哪些位置的符号没有变更过,就说明原数组里面没有这个位置的下标对应的数字。element

相关文章
相关标签/搜索