forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 6
/
single-number-iii.py
45 lines (40 loc) · 1.12 KB
/
single-number-iii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Time: O(n)
# Space: O(1)
#
# 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:
# @param {integer[]} nums
# @return {integer[]}
def singleNumber(self, nums):
x_xor_y = reduce(operator.xor, nums)
bit = x_xor_y & -x_xor_y
result = [0, 0]
for i in nums:
result[bool(i & bit)] ^= i
return result
class Solution2:
# @param {integer[]} nums
# @return {integer[]}
def singleNumber(self, nums):
x_xor_y = 0
for i in nums:
x_xor_y ^= i
bit = x_xor_y & ~(x_xor_y - 1)
x = 0
for i in nums:
if i & bit:
x ^= i
return [x, x ^ x_xor_y]