码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 137. Single Number I/II/III

时间:2016-11-21 08:48:01      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:并且   ever   code   hash   ber   word   appear   dict   etc   

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

标签:并且   ever   code   hash   ber   word   appear   dict   etc   

原文地址:http://www.cnblogs.com/lettuan/p/6084174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!