Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 3fc7d3d

Browse files
aQuaaQua
aQua
authored and
aQua
committed
268 finish
1 parent 88a5a9e commit 3fc7d3d

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

Algorithms/0268.missing-number/README.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ Your algorithm should run in linear runtime complexity. Could you implement it u
1616

1717

1818
## 解题思路
19+
`^`:按位异或运算符,是双目运算符。 其功能是参与运算的两数各对应的二进位相异或,当两对应的二进位相异时,结果为1。
1920

21+
特别地,`^`支持交换律
22+
```
23+
1^1^2^2^3^3 == 1^2^2^3^3^1 == 1^3^2^3^1^2
24+
```
2025

21-
见程序注释
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
11
package Problem0268
22

33
func missingNumber(nums []int) int {
4-
for i := 0; i < len(nums); i++ {
5-
for nums[i] < len(nums) && nums[i] != i {
6-
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
7-
}
8-
}
4+
xor := 0
95

106
for i, n := range nums {
11-
if i != n {
12-
return i
13-
}
7+
xor ^= i ^ n
148
}
15-
16-
return len(nums)
9+
// 所有的 i 再加上 len(nums),就相当于 0,1,...,n。
10+
// 利用 相同的数 异或 为0,及其交换律
11+
// xor 最后的值,就是那个缺失的数
12+
return xor ^ len(nums)
1713
}

0 commit comments

Comments
 (0)