糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > Leetcode 137. Single Number I/II/III

Leetcode 137. Single Number I/II/III

时间:2018-12-21 23:53:51

相关推荐

Leetcode 137. Single Number I/II/III

Given an array of integers, every element appearstwiceexcept for one. Find that single one.

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

1 class Solution(object): 2def singleNumber(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 s = 0 8 for x in nums: 9 s= s^x10 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]] = 1else:dict[nums[i]] += 1for word in dict:if dict[word] == 1:return word

如果觉得《Leetcode 137. Single Number I/II/III》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。