448. Find All Numbers Disappeared in an Array

来源:互联网 发布:springmvc 项目源码 编辑:程序博客网 时间:2024/04/30 08:44

题意: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]

思路:这类题目不考虑元素先后关系,肯定不需要用set或者dict,又限制了空间复杂度,所以肯定只能在原数组上操作,所以肯定是使用元素和索引的关系,我的方法是给数组中出现过的元素索引位对应的数加上数组的长度,这样不仅能通过%又重新定位到索引上,而且最后只要元素小于等于数组长度的,就是消失的数:

    def findDisappearedNumbers(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        ans = []        for i in xrange(len(nums)):            nums[(nums[i]-1)%len(nums)] += len(nums)        for i in xrange(len(nums)):            if nums[i] <= len(nums):                ans.append(i+1)        return ans

当然也可以用取反的方法,这是别人的方法:

class Solution(object):    def findDisappearedNumbers(self, nums):        """        :type nums: List[int]        :rtype: List[int]        """        for i in xrange(len(nums)):            if nums[abs(nums[i]) - 1] > 0:                nums[abs(nums[i]) - 1] *= -1        result = []        for i in xrange(len(nums)):            if nums[i] > 0:                result.append(i+1)            else:                nums[i] *= -1    return result
0 0
原创粉丝点击