文章目录[隐藏]
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
code
- python
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# 应该的总和 - 实际的总和
return (len(nums) * (len(nums) + 1)) // 2 - sum(nums) # 利用公式求和
- python
0^m = m , m^m = 0
class Solution:
def missingNumber(self, nums: List[int]) -> int:
ret = 0
for i in range(len(nums)):
ret ^= i ^ nums[i]
return ret ^ len(nums)