您的位置:首页 > 编程语言 > Python开发

LeetCode 260. Single Number III Python Solution

2017-10-11 17:01 489 查看
此题目对应于 LeetCode 260

题目要求:

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
给一个数组,其中每个元素都出现了两次除了两个元素,那两个元素只出现一次,要求找出那两个个元素。要求时间O(n),空间最好O(1)。

这里提供一个时间O(n),空间O(n)的解法。

这个是 LeetCode 136. Single Number问题的深化版,在解这个问题的时候需要用到我之前两个文章的知识,LeetCode
136. Single Number

和 Python Lowbit 。

解法思路就是把原拆分成2个数组,每一个数组包含一个只出现一次的元素,在调用LeetCode
136. Single Number的解法。

那怎么进行拆分呢?

1.将数组元素从头得到一个值。

2.根据这个值对应2进制从右边起第一个1,将原数组分拆成2份。

由于存在2个只出现一次的数,那么异或结果肯定非0,既一定能找到这样的一个1。根据对应位是否为1即可以将原数组分拆

成2份。由于或为1则表示,这2个数字对应2进制在该位上数值不一样即一个为0,一个为1。

下面附上Python代码。

class Solution(object):
def presingle(self,nums):
tmp = 0
for i in nums:
tmp^=i
return tmp
def singleNumber(self, nums):
tmp = self.presingle(nums)
tag = 0
tmp &= -tmp
num1 = []
num2 = []
for i in nums:
if i&tmp==tmp:
num1.append(i)
else:
num2.append(i)
return [self.presingle(num1),self.presingle(num2)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息