70 leetcode - Single Number I,II,III

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])


• 本文已收录于以下专栏：

举报原因： 您举报文章：70 leetcode - Single Number I,II,III 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)