Single Number
标准异或的定义,python利用reduce函数一行就可以搞定了
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x ^ y, nums)
Single Number II
这题有两种做法,都不是很记得解题思路了,先把代码写下来,下面这种是数三出现的次数,比较好理解
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in xrange(32):
base = 1 << i
count = 0
for num in nums:
if num & base:
count += 1
if count % 3:
res |= base
return res if abs(res) < abs(2 ** 32 - res) else res - 2 ** 32
另外还有bit位操作的方法,完全不知道是什么原理了
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a0, a1 = 0, 0
for num in nums:
a0 = (a0 ^ num) & (~a1)
a1 = (a1 ^ num) & (~a0)
return a0
Single Number III
这里利用了一个找最低bit位的方法
两遍pass,第一遍找到两个结果的异或和,再找到这个异或和的最低位1,这个位就是两个结果不同的位,拿这个最低位1当bitmask去找就能分别找到两个数的结果了
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
sumOfTwoElements = 0
for num in nums:
sumOfTwoElements ^= num
bitMask = sumOfTwoElements & (sumOfTwoElements ^ (sumOfTwoElements - 1))
tmp = 0
for num in nums:
if num & bitMask:
tmp ^= num
result = [tmp, sumOfTwoElements ^ tmp]
return result