题目
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
中文大意
给定一个整数数组,里面只有一个数只出现一次,其余的数都出现两次,找出只出现一次的数。
解题思路
采用异或运算^
a ^ a = 0
a ^ 0 = a
a ^ b ^ c = a ^ (b ^ c)
因此所有数进行异或,最终得到的就是只出现一次的数
代码
func singleNumber(nums []int) int {
var ret int
ret = 0
for _,v := range nums {
ret = ret ^ v
}
return ret
}