[LeetCode]Find All Numbers Disappeared in an Array

题目描述:

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.

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

Example:

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

Output:
[5,6]

题目大意:

给定一个整数数组,其中1 ≤ a[i] ≤ n (n = 数组长度),一些元素出现两次,其他的出现一次。

寻找所有[1, n]中没有出现在数组中的元素。

可以不使用额外空间并在O(n)运行时间求解吗?你可以假设返回列表不算额外空间。

解题思路:

正负号标记法

遍历数组nums,记当前元素为n,令nums[abs(n) - 1] = -abs(nums[abs(n) - 1])

再次遍历nums,将正数对应的下标+1返回即为答案,因为正数对应的元素没有被上一步骤标记过。

Python代码:

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

 

本文链接:http://bookshadow.com/weblog/2016/11/01/leetcode-find-all-numbers-disappeared-in-an-array/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码