描述
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
分析
方法1:遍历数组,借助map保存已遍历过的数据的重复次数。最后遍历map,返回重复次数为奇数的键值。
方法2:因为题目明确数组中重复奇数次数的数据项只有一个,那么其它数据项出现次数是偶数次,这些数据项经过偶数次抑或会变为0,而奇数次数的数据项经过抑或后,结果就是该奇数本身。
实现
方法1:
func FindOdd(seq []int) int {
dict := map[int]int{}
for _, v := range seq { dict[v]++ }
for k, v := range dict {
if v % 2 == 1 { return k }
}
return 0
}
方法2:
func FindOdd(seq []int) (res int) {
for _, n := range seq {
res ^= n
}
return
}