Day1:寻找孤独的哪一个

leetcode:136


<b>Question</b>(leetcode:136): Given an array of integers, every element appearstwiceexcept for one. Find that single one.(给定一个整型数组,每一个元素出现两次,只有一个元素出现一次,找到这个元素)

        import operator
        class Solution:    
                def singleNumber(self,A):
                      return reduce(operator.xor,A)
        if __name__ == '__main__':    
               print Solution().singleNumber([1,1,2,3,2,4,4])
  1. 其中我们导入了python的operator的库,这个库主要提供一些基本的函数操作,这个函数中主要使用xor函数(异或函数)
        xor(a,b) -> same as a ^ b
  1. 我们用到了python的高阶函数-reduce

reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

    reduce(operato.xor,A) 等于下面
   (( (1 ^ 1) ^ 2) ^ 3).....
  1. 核心是((a ^ b) ^ a) = b

leetcode:137


<b>Question</b>: Given an array of integers, every element appears three times except for one. Find that single one.(给定一个数组,每一个元素出现3次,除了一个找到这一个)

        class Solution3:    
               def singleNumber(self,A ):
                    one,two,three = 0,0,0        
                    for x in A:            
                    #是否是第二次相同            
                    two = one & x | two
                    one = one ^ x
                    three = one & two
                    one = one & ~three
                    two = two & ~three
                    print 'one:%x,two:%x,three:%x' % (one,two,three)
        if __name__ == '__main__':
                    print Solution3().singleNumber([4,4,3,4,1,1,1,2,3,3])
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容