leetcode刷题(四)

问题地址:https://leetcode.com/problems/single-number/description

问题描述:在一个数组里只有这数字出现一次,其他数字出现两次,输出这个数字。要求时间复杂度为O(n),空间负责度为O(1)。

解决思路:按位逻辑异或,当数组中数字相同时,结果输出为0,最后一个与数字与0相异或,得到的结果仍然为该数字。

    异或值
0 0 0
0 1 1
1 0 1
1 1 0

代码如下:

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

        return nums[0]

性能截图如下(表现相当不错):


猜你喜欢

转载自blog.csdn.net/weixin_38368941/article/details/79888013