`260. Single Number III
Medium
2732
152
Add to List
Share
Given an integer array 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. You can return the answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
Example 1:
Input: nums = [1,2,1,3,2,5]
Output: [3,5]
Explanation: [5, 3] is also a valid answer.
Example 2:
Input: nums = [-1,0]
Output: [-1,0]
Example 3:
Input: nums = [0,1]
Output: [1,0]
Constraints:
2 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
Each integer in nums will appear twice, only two integers will appear once.`
single num 加加强版, 首先先求异或值, 因为两个独特的数字, 所以异或值不为0, 找到不为0的二进制最小位数. 然后对nums中所有该位不为0的数字进行与或求得其中一个数的值
`class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
xor_result = 0
for i in nums:
xor_result ^= i
pos = -1
for i in range(128):
if (xor_result & 1 << i) == 1 << i:
pos = i
break
else:
raise Exception
x = 0
for i in nums:
if (i & 1 << pos) == 1 << pos:
x ^= i
y = xor_result ^ x
return [x, y]`