首页 > 其他 > 详细

[Leetcode] 136. Single Number

时间:2020-04-06 10:44:06      阅读:52      评论:0      收藏:0      [点我收藏+]

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 对应位上完全相反

[Leetcode] 136. Single Number

原文:https://www.cnblogs.com/codingEskimo/p/12640417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!