剑指Offer-56 数组中只出现一次的两个数字

题目:

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。你可以假设这两个数字一定存在。
样例
输入:[1,2,3,3,4,4]
输出:[1,2]

解答:

class Solution(object):
	def findNumsAppearOnce(self, nums):
		"""
		:type nums: List[int]
		:rtype: List[int]
		"""
		xor = 0
		for i in nums:
			xor = xor ^ i
		count = 0
		while(xor != 0):
			r = xor & 0b1
			count += 1
			if r == 1:
				break
			else:
				xor = xor >> 1
		count -= 1
		split = 1
		while(count > 0):
			split = split << 1
			count -= 1
		first, second = 0, 0
		for i in nums:
			if i & split == 0:
				first = first ^ i
			else:
				second = second ^ i 
		return [first, second]

猜你喜欢

转载自blog.csdn.net/u013796880/article/details/84888642
今日推荐