Skip to content

Commit e7ad463

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 19.1 MB (65.46%)
1 parent 9ae992a commit e7ad463

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p>
2+
3+
<p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [1,2,1,3,2,5]
10+
<strong>Output:</strong> [3,5]
11+
<strong>Explanation: </strong> [5, 3] is also a valid answer.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [-1,0]
18+
<strong>Output:</strong> [-1,0]
19+
</pre>
20+
21+
<p><strong class="example">Example 3:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> nums = [0,1]
25+
<strong>Output:</strong> [1,0]
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
33+
<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
34+
<li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li>
35+
</ul>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution:
2+
def singleNumber(self, nums: List[int]) -> List[int]:
3+
xor_val = reduce(xor, nums)
4+
val1 = 0
5+
low_bit = xor_val & -xor_val
6+
7+
for num in nums:
8+
if num & low_bit:
9+
val1 ^= num
10+
val2 = xor_val ^ val1
11+
12+
return [val1, val2]

0 commit comments

Comments
 (0)