LeetCode136只出现一次的数字
LeetCode136只出现一次的数字
未经博主同意,禁止瞎JB转载。
https://leetcode-cn.com/problems/single-number/description/
我的解法:
字典(哈希)
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ret = {} for i in nums: if i in ret: ret.pop(i) else: ret[i] = 1 return ret.keys()[0]
别人的解法:
异或:0异或任何数不变,任何数与自己异或为0。a⊕b⊕a=b。异或满足加法结合律和交换律。 1^2 = 3, 1^3 = 2, 转为二进制逐位异或
代码:
class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 for i in nums: res^=i return res