首页 > 代码库 > Leetcode 137. Single Number I/II/III
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满足交换律。
1 class Solution(object): 2 def singleNumber(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 s = 0 8 for x in nums: 9 s= s^x 10 11 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
Leetcode 137. Single Number I/II/III
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。