您的位置:首页 > 其它

LeetCode:Single Number II

2014-10-16 17:28 363 查看
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?
这种题目一般都用位运算。考虑32位的数字,如果某一位出现3次,则记为0。最后剩下1的就是多出来那个数字本身含有的。

class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
l=[]
x=0
minus=0
for i in range(32):
l.append(0)#创建个32的列表,起始都是0
for j in A:
if j<0:#负数位移有点问题,不是简单的右移,还要计算,为了简单运算,负数转正数
j=-j
minus=minus+1#同时记录负数的个数,如果最后不是3的倍数,说明所求的数字是负数
for i in range(32):
l[i]=l[i]+ ((j>>i)&1)#不断右移,是1的位数上加1
if l[i]==3:#是3,清零
l[i]=0
for i in range(32):
if l[i]==1:
x=x+2**i#通过2进制把数算出来
if minus%3!=0:
x=-x#是负数?
return x
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: