1.异或
2.字典或集合
3.排序
golang语言采用异或方式,代码如下:
package test21_singlenumber
import (
"fmt"
"testing"
)
//go test -v -test.run TestSingleNumber
func TestSingleNumber(t *testing.T) {
arr := []int{3, 1, 2, 1, 3, 4, 4}
fmt.Println("数组:", arr)
fmt.Println("结果:", singleNumber(arr))
}
func singleNumber(nums []int) int {
single := 0
for _, num := range nums {
single ^= num
}
return single
}
敲go test -v -test.run TestSingleNumber命令,结果如下: