Leetcode 137. Single Number I/II/III
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-137-Single Number II]