[Leetcode] 136. Single Number

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

这道题比较直观的做法就是用hashmap,然后循环找到value是一个的就行了。但是follow up要求的是空间为1,那么hashmap就不行了。这里面要用异或xor操作,当一个数字两次被xor,那么相当于没有对其操作,,因为相同的数字两次xor对原来的数字就没有影响。下边这是几个非常有代表性的解法

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
    
def singleNumber3(self, nums):
    return 2*sum(set(nums))-sum(nums)
    
def singleNumber4(self, nums):
    return reduce(lambda x, y: x ^ y, nums)
    
def singleNumber(self, nums):
    return reduce(operator.xor, nums)

补充知识, 位操作:

a = 0011 1100

b = 0000 1101

a&b 0000 1100 只有对应位上都是1才会是1,其余是0,任何数和0与都是0
aorb 0011 1101 只有对应为上都是0才会是0,其余是1,任何数和1或最后一位都是1
a^b 0011 0001 对应位上相同就是0不同就是1,任何数异或两次就对于原来的数没有影响。
a~ 1100 0011 对应位上完全相反

异或 => 无进位相加

  • a^0 = a
  • a^a = 0
  • a^b = b^a
  • abc = a(bc)
  • 得到一个数二进制最右位为1,其余为0的模:a &(~a+1) (~a + 1) = -a =>这道题用不上,但这个知识点很有用。

posted on 2020-04-06 05:35  codingEskimo  阅读(110)  评论(0编辑  收藏  举报

导航