美文网首页
136. 只出现一次的数字

136. 只出现一次的数字

作者: 葡萄肉多 | 来源:发表于2019-10-15 22:16 被阅读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

题意

找出一个非空数组中只出现一次的数字,除了这个数,其他数都出现了两次。

思路

位运算。
相同的数异或为0,一个数异或0为它本身。

代码

class Solution:
    def singleNumber(self, nums):
        res = 0
        for i in nums:
            res ^= i
        return res

相关文章

网友评论

      本文标题:136. 只出现一次的数字

      本文链接:https://www.haomeiwen.com/subject/thpemctx.html