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