# 70 leetcode - Single Number I,II,III

56人阅读 评论(0)

## Single Number I

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length == 0:
return 0
if length == 1:
return nums[0]

return reduce(lambda x,y:x^y,nums)

## Single Number II

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Single Number II
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?

'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length == 0:
return 0

bit_sum = [0] * 32
for val in nums:
for index in range(32):
bit_sum[index] += (val >> index) & 1

ret = 0
#print bit_sum
for index,val in enumerate(bit_sum[:-1]):
ret += (val%3)<<index
if bit_sum[-1]%3 == 1:
return -(pow(2,31) - ret)
return ret

if __name__ == "__main__":
s = Solution()
print s.singleNumber([1,3,3,3])
print s.singleNumber([1])
print s.singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2])
print s.singleNumber([-401451,-177656,-2147483646,-473874,-814645,-2147483646,-852036,-457533,-401451,-473874,-401451,-216555,-917279,-457533,-852036,-457533,-177656,-2147483646,-177656,-917279,-473874,-852036,-917279,-216555,-814645,2147483645,-2147483648,2147483645,-814645,2147483645,-216555])



## Single Number III

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
'''
class Solution(object):
def __single(self,nums):
ret = nums[0]
for i in nums[1:]:
ret = ret ^ i

return ret

def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
if length <= 2:
return nums

#两个只出现一次的数异或
tmp = self.__single(nums)

diff_index = 0
#寻找能区分两个数的那一位,因为tmp做的是异或
while diff_index < 32:
if (tmp >> diff_index) & 1:
break

diff_index += 1

#转换成了一个数组中有一个数出现一次,其余出现两次
ret1 = ret2 = 0
for i in nums:
if (i>>diff_index) & 1:
ret1 = ret1 ^ i
else:
ret2 = ret2 ^ i

return [ret1,ret2]

if __name__ == "__main__":
s = Solution()
print s.singleNumber([1,2,3,3,4,4,2,5,5,10])

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
阅读排行
博客专栏
 关注Python细节,第三方包学习 文章：43篇 阅读：16473
个人资料
• 访问：31135次
• 积分：2000
• 等级：
• 排名：第19474名
• 原创：176篇
• 转载：12篇
• 译文：0篇
• 评论：2条
评论排行