https://leetcode.com/problems/single-number-iii
260. Single Number III
给定一数列 此数列只有两个数字单独出现 其他元素都成双成对
请回传单独出现的两个数字
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.
思路:
哈希表纪录出现次数
Python Code:
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
res = []
map = defaultdict(int)
for n in nums:
map[n] += 1
for k,v in map.items():
if v == 1:
res.append(k)
if len(res) == 2:
return res
应该有位运算解法 但我试不出来 告辞