LeetCode136: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

LeetCode:链接

LeetCode变体:LeetCode137:Single Number II

LeetCode260:Single Number III

剑指Offer_编程题40:数组中只出现一次的数字(异或)的简单版。

^ 按位异或运算符:当两对应的二进位相异时,结果为1

任何一个数字异或它自己都等于0 。也就是说,如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现一次的数字。比如数组{4,5,5},我们先用数组中的第一个元素4(二进制形式:0100)和数组中的第二个元素5(二进制形式:0101)进行异或操作,0100和0101异或得到0001,用这个得到的元素与数组中的三个元素5(二进制形式:0101)进行异或操作,0001和0101异或得到0100,正好是结果数字4。这是因为数组中相同的元素异或是为0的,因此就只剩下那个不成对的孤苦伶仃元素。

A和0异或的结果还是A
 

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        remain = 0
        for num in nums:
            remain ^= num
        return remain

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84866086