1.異或
2.字典或集合
3.排序
golang語言采用異或方式待诅,代碼如下:
package?test22_singlenumber3
import?(
"fmt"
? ??"testing"
)
//go test -v -test.run TestSingleNumber
func?TestSingleNumber(t *testing.T) {
? ??arr := []int{3,?1,?2,?1,?3,?4,?4,?5}
? ??fmt.Println("數組:",?arr)
? ??fmt.Println("結果:",?singleNumber(arr))
}
func?singleNumber(nums []int) []int?{
? ??eorsum :=?0?//兩個單數的按位異或
? ??for?i :=?len(nums) -?1;?i >=?0;?i-- {
? ?? ???eorsum ^= nums[i]
? ??}
? ??rightbit1 := eorsum & ((^eorsum) +?1)?//取eorsum最右邊的1
? ??retone :=?0?//其中一個單數
? ??for?i :=?len(nums) -?1;?i >=?0;?i-- {
? ?? ???if?nums[i]&rightbit1 !=?0?{
??? ??? ????retone ^= nums[i]
?? ?????}
? ??}
? ??return?[]int{eorsum ^ retone,?retone}
}
敲go test -v -test.run TestSingleNumber命令,結果如下: