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
應該有位運算解法 但我試不出來 告辭