[Lintcode]82. Single Number/[Leetcode]136. Single Number

82. Single Number/136. Single Number

  • 本题难度: Easy
  • Topic: Greedy

Description

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1
Example 2:

Input: [4,1,2,1,2]
Output: 4

我的代码

class Solution:
    """
    @param A: An integer array
    @return: An integer
    """
    def singleNumber(self, A):
        # write your code here
        res = 0
        for i in A:
            res = res^i
        return res

别人的代码 参考

#开辟一个字典
def singleNumber1(self, nums):
    dic = {}
    for num in nums:
        dic[num] = dic.get(num, 0)+1
    for key, val in dic.items():
        if val == 1:
            return key

#异或
def singleNumber2(self, nums):
    res = 0
    for num in nums:
        res ^= num
    return res
    
#利用了set
def singleNumber3(self, nums):
    return 2*sum(set(nums))-sum(nums)

#reduce
#异或    
def singleNumber4(self, nums):
    return reduce(lambda x, y: x ^ y, nums)
    
#reduce
#异或
def singleNumber(self, nums):
    return reduce(operator.xor, nums)

思路

相同的数字,异或为0

  • 时间复杂度 O(log(n))
上一篇:android – 如何在zxing中触发批量模式扫描


下一篇:lintcode 丢鸡蛋