LeetCode136.python实现: 只出现一次的数字☆

目录

一、问题

二、解题思路

三、python具体实现

四、题外话


一、问题

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

示例 1:

输入: [2,2,1]
输出: 1

示例 2:

输入: [4,1,2,1,2]
输出: 4

二、解题思路

    分析:异或运算性质的考察:相同为0,不同为1. 异或同一个数两次,原数不变。(与0相异或,保留原值)

三、python具体实现

使用了2字节额外空间:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = 0
        for i in nums:
            result = result^i   # 异或操作
        return result

不使用额外空间实现:

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

四、题外话

     知道异或就会很简单,不知道就难住了。学到了! 

猜你喜欢

转载自blog.csdn.net/weixin_42521211/article/details/88388020
今日推荐