您的位置:首页 > 编程语言 > Go语言

【Leetcode】:Single Number II问题 in Go语言

2016-04-13 18:09 513 查看
Given an array of integers, every element appears three times except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

这道题比同类的另外两个问题解决起来都要复杂,其核心思路就是“计满三个就清零”,for循环每次处理一个nums中的数,对这个数的

每一个特比进行计算,只要1出现3次便重置为0,那么nums数组中的所有出现3次的数的相应bit位一定为0

参考“http://www.tuicool.com/articles/fAZZv2a”

func singleNumber(nums []int) int {
one := 0
two := 0
three := 0
for _, v := range nums {
two = two | (one & v) //计算每个比特位中的1是否出现了两次
one = one ^ v         //计算每个比特位是否出现了一次或三次
three = one & two     //当one和two的相应位为1时,表示相应位出现了3次
one = one & (^three)  //当相应位出现了3次时,把相应的位出现次数置为0
two = two & (^three)
}
return one
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Golang go语言