leetcode 上令我醍醐灌顶的编程思维 --448 消失的数

题目如下:

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-n的整形数组,其中有的数出现两次,有的只出现一次,找出从1-n中未出现的数。。。
    在O(n)的时间内和不用额外空间,你能do it 吗?可以假定,返回的list不计入额外空间。

精彩代码如下:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for i in xrange(len(nums)):
            index = abs(nums[i]) - 1
            nums[index] = - abs(nums[index])

        return [i + 1 for i in range(len(nums)) if nums[i] > 0]

遍历list,将出现的值减1,即为出现的数的key,然后将其key所在值赋为负值。(加绝对值是为了防止重复出现的值变为正数)

然后再次遍历,value不为负值的,其key+1(key要再加一),即为未出现过的值。

取key赋为负值,真的6。。。。。我脑子可能真的有坑。。。

最后一行代码表示,返回遍历list,如果nums[i]值大于0,则返回其i+1(即key+1)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值