Leetcode 刷题 - 268 - Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


根据题意,给一个list,没有重复数字,从0开始到n。但是中间有一个数字不见了。需要找到并输出这个数字。


很简单的两种方法

class Solution(object):
    def missingNumber(self, nums):
        return (set(range(len(nums)+1)) - set(nums)).pop()

利用set的bit操作,剩下的就是我们需要的missing number

class Solution(object):
    def missingNumber(self, nums):
        return (len(nums) + 1) * len(nums) / 2 - sum(nums)

利用的是数学的求和公式,0~n,和就是((N+1)*N)/2, 然后减去给定的list,就能找到missing number。


题目的提示的bit manipulation,我们可以用异或XOR来得到结果。

class Solution(object):
    def missingNumber(self, nums):
        x = nums[0] # nums will be [0,1,2,..n] => nums[0] = 0
        y = 0
        for i in range(1, len(nums)):
            x ^= nums[i] # XOR all numbers
            y ^= i # same like above
        y ^= len(nums) # one number is missing, means totally have len(nums) numbers
        return x^y

因为,loop的值和index是一样的,都从0开始到n。但是因为有missing number,所以index是完全的0~n,而value值是缺少一个数字的。

所以最后index的异或和value值的异或,就会把missing number找到。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值