- leetcode single number的三道题目
- 代码及实现
- 总结及归纳
I.leetcode single number的三道题目
①有一个数字出现一次,其余数字出现两次,找出此数
②有一个数字出现一次,其余数字出现三次,找出此数
③有两个数字均只出现一次,其余数字出现两次,找出此数
II. 代码及实现
①
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
temp=0
for i in range(0,len(nums)):
temp=temp^nums[i]
return temp
②
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ones,twos=0,0
for elem in nums:
ones=ones^elem & ~twos
twos=twos^elem & ~ones
return ones
③
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
xor=0
for elem in nums:
xor^=elem
lowbit = xor & -xor
a = b = 0
for num in nums:
if num & lowbit:
a ^= num
else:
b ^= num
return [a, b]
III. 总结及归纳
⑴
②解释:
ones=ones^elem & ~twos
twos=twos^elem & ~ones
当ele第一次出现时,因为ones和twos都初始化为0,所以很显然运行这两行代码后ones=ele,twos=0.
在此之后如果ele不再出现,那么很显然这就是只出现一次的数字,ones即为最终结果,如果它第二次出现,ones将会被清零,而twos则会储存下ele的值。
③解释:[http://bookshadow.com/weblog/2015/08/17/leetcode-single-number-iii/]
首先计算nums数组中所有数字的异或,记为xor
令lowbit = xor & -xor,lowbit的含义为xor从低位向高位,第一个非0位所对应的数字
例如假设xor = 6(二进制:0110),则-xor为(二进制:1010,-6的补码,two’s complement)
则lowbit = 2(二进制:0010)
根据异或运算的性质,“同0异1”
记只出现一次的两个数字分别为a与b
可知a & lowbit与b & lowbit的结果一定不同
通过这种方式,即可将a与b拆分开来
⑵让我们一同努力,明天会更好!