Leetcode Missing Number Python 如何找出数组中缺少的值,异或方法。

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.

Example 1:

Input: [3,0,1]
Output: 2
Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

题目大意:给出一组缺少一个值的乱序数组,求出这个值。

做这道题的时候我蠢了,直接用not in 判断了。本来以为简单到不用写上来,结果还是我思考的不周到。

其实这道题有两个方法,一个数学法,一个异或法。
数学法:

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        nums_total = sum(nums)
        length = len(nums)
        total = (length * (length+1)) // 2
        return total - nums_total

一个数字降序递加到0,等于这个数字乘这个数字加一再除以2.

异或法:
先学习异或的概念。在我的这篇文章中。
https://blog.csdn.net/weixin_43860294/article/details/104890947

主要概念是:

异或的性质:

1、交换律:a^b = b^a;

2、结合律:(a^b)^c = a^(b^c);

3、对于任意的a:a^a=0,a^0=a,a^(-1)=~a。

主要用来做消重。

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        res = len(nums)
        for i in range(len(nums)):
            res = res ^ (i ^ nums[i])
        return res

res = res ^ (i ^ nums[i]) 数字异或本身等于0, 0异或任何数都等于数字本身。

疫情中的英国,
回国的机票真贵,
加油!
22/05/2020

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值