Single Number

来源:互联网 发布:windowsce软件 编辑:程序博客网 时间:2024/05/22 04:33

题目详情:https://leetcode.com/problems/single-number/description/
整数数组中的每个元素都出现两次,只有某个元素只出现了一次,找出该元素

# -*- coding:utf-8 -*-class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        dist={}        s=0        iSum=0        for i in nums:            s+=i #            if dist.get(i,-1)==-1: #不存在的话,执行以下两个代码                dist[i]=True #将不存在的值添加进去                iSum=iSum+i*2 #不重复的更新iSum的值,        return iSum-s

看见大神的代码,又膜拜了

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        #  A XOR A = 0 and the XOR operator is commutative        xor_result = 0        for a_num in nums:            xor_result ^= a_num        return xor_result

^ 为异或运算符。按二进制的位进行异或处理,位数相异,异或为1。两个数相同,进行异或后为0。
[1,1,3,3,4],[1,3,1,3,4]用上述代码处理之后,最后结果相同,异或满足交换律。

原创粉丝点击