268. 丢失的数字
考点
- 异或技巧
题解
1 | class Solution { |
时间复杂度:\(O\left( n \right)\),其中\(n\)为数组长度
空间复杂度:\(O\left( 1 \right)\)
思路
假设给定范围为\(a_{0...3}\),nums
的值为\(\left\{ a_0,a_1,a_3
\right\}\),则需要找到\(a_2\)
根据异或的性质a ^ a = 0
与a ^ 0 = a
,必有以下恒等式成立:
\[
\left( a_0\oplus a_1\oplus a_2\oplus a_3 \right) \oplus \left( a_0\oplus
a_1\oplus a_3 \right) =a_2
\]
故而先求出0 ~ nums.size()
的异或和,再与nums
的元素逐个异或即可得出缺失的元素