website/content/ChapterFour/0100~0199/0137.Single-Number-II.md
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。要求算法时间复杂度是线性的,并且不使用额外的辅助空间。
三进制(00,01,10) 就可以做到。在 golang 中,&^ 表示 AND NOT 的意思。这里的 ^ 作为一元操作符,表示按位取反 (^0001 0100 = 1110 1011),X &^ Y 的意思是将 X 中与 Y 相异的位保留,相同的位清零。
在 golang 中没有 Java 中的 ~ 位操作运算符,Java 中的 ~ 运算符代表按位取反。这个操作就想当于 golang 中的 ^ 运算符当做一元运算符使用的效果。
| (twos,ones) | xi | (twos'',ones') | ones' |
|---|---|---|---|
| 00 | 0 | 00 | 0 |
| 00 | 1 | 01 | 1 |
| 01 | 0 | 01 | 1 |
| 01 | 1 | 10 | 0 |
| 10 | 0 | 10 | 0 |
| 10 | 1 | 00 | 0 |
| (twos,ones') | xi | twos' |
|---|---|---|
| 00 | 0 | 0 |
| 01 | 1 | 0 |
| 01 | 0 | 0 |
| 00 | 1 | 1 |
| 10 | 0 | 1 |
| 10 | 1 | 0 |
这一题还可以继续扩展,在数组中每个元素都出现 5 次,找出只出现 1 次的数。那该怎么做呢?思路还是一样的,模拟一个五进制,5 次就会消除。代码如下:
// 解法一
func singleNumberIII(nums []int) int {
na, nb, nc := 0, 0, 0
for i := 0; i < len(nums); i++ {
nb = nb ^ (nums[i] & na)
na = (na ^ nums[i]) & ^nc
nc = nc ^ (nums[i] & ^na & ^nb)
}
return na & ^nb & ^nc
}
// 解法二
func singleNumberIIII(nums []int) int {
twos, threes, ones := 0xffffffff, 0xffffffff, 0
for i := 0; i < len(nums); i++ {
threes = threes ^ (nums[i] & twos)
twos = (twos ^ nums[i]) & ^ones
ones = ones ^ (nums[i] & ^twos & ^threes)
}
return ones
}
package leetcode
func singleNumberII(nums []int) int {
ones, twos := 0, 0
for i := 0; i < len(nums); i++ {
ones = (ones ^ nums[i]) & ^twos
twos = (twos ^ nums[i]) & ^ones
}
return ones
}
// 以下是拓展题
// 在数组中每个元素都出现 5 次,找出只出现 1 次的数。
// 解法一
func singleNumberIIIII(nums []int) int {
na, nb, nc := 0, 0, 0
for i := 0; i < len(nums); i++ {
nb = nb ^ (nums[i] & na)
na = (na ^ nums[i]) & ^nc
nc = nc ^ (nums[i] & ^na & ^nb)
}
return na & ^nb & ^nc
}
// 解法二
func singleNumberIIIII1(nums []int) int {
twos, threes, ones := 0xffffffff, 0xffffffff, 0
for i := 0; i < len(nums); i++ {
threes = threes ^ (nums[i] & twos)
twos = (twos ^ nums[i]) & ^ones
ones = ones ^ (nums[i] & ^twos & ^threes)
}
return ones
}