Leetcode 137. Single Number I/II/III

时间:2023-03-09 21:39:33
Leetcode 137. Single Number I/II/III

Given an array of integers, every element appears twice except for one. Find that single one.

本题利用XOR的特性, X^0 = X, X^X = 0, 并且XOR满足交换律。

 class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = 0
for x in nums:
s= s^x return s

single number II/III可以用位操作。用Hash table也可以通过OJ

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict = {}
for i in range(len(nums)):
if nums[i] not in dict:
dict[nums[i]] = 1
else:
dict[nums[i]] += 1 for word in dict:
if dict[word] == 1:
return word