<h3><a title="题目描述" href="https://leetcode-cn.com/problems/missing-number/">题目描述</a></h3>
<img src="https://i.loli.net/2019/11/20/IShXZdq5OCuex3W.png" alt="file" />
<h4>我的:字典解法</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="null">class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
flag = dict()
for num in nums:
flag[num] = 1
for num in range(n+1):
if num not in flag:
return num</pre>
<p> </p>
<h4>数学解法</h4>
<p>思路就是高斯求和公式先求出[0,1,···,n]的和,再减去数组中所有数字的和,就是缺失的数字。</p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">class Solution:
def missingNumber(self, nums):
expected_sum = len(nums)*(len(nums)+1)//2
actual_sum = sum(nums)
return expected_sum - actual_sum
</pre>
<p> </p>
<h4>位运算解法</h4>
<img src="https://i.loli.net/2019/11/20/49VHruMQNigeKtm.png" alt="file" />
<pre class="EnlighterJSRAW" data-enlighter-language="null">class Solution:
def missingNumber(self, nums):
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing
</pre>
<p> </p>
<h4>Note</h4>
<ul>
<li>简单题</li>
<li>但是思路其实很多 , 开阔视野开阔思路吧。</li>
</ul>
Leetcode268 缺失数字