Skip to content

Commit 884d4cc

Browse files
committed
Single Number III
1 parent eacff63 commit 884d4cc

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

260-single-number-iii.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/single-number-iii/
3+
4+
Given an array of numbers nums, in which exactly two elements appear only once and all the
5+
other elements appear exactly twice. Find the two elements that appear only once.
6+
7+
Example:
8+
Input: [1,2,1,3,2,5]
9+
Output: [3,5]
10+
11+
Note:
12+
The order of the result is not important. So in the above example, [5, 3] is also correct.
13+
Your algorithm should run in linear runtime complexity. Could you implement it using only
14+
constant space complexity?
15+
"""
16+
class Solution:
17+
def singleNumber(self, nums: List[int]) -> List[int]:
18+
xor = 0
19+
for no in nums:
20+
xor ^= no
21+
res = [0, 0]
22+
xor &= -xor
23+
for no in nums:
24+
if xor & no == 0:
25+
res[0] ^= no
26+
else:
27+
res[1] ^= no
28+
return res

0 commit comments

Comments
 (0)