Python实现"只出现一次的数字"的三种方法

给定一个非空的整数数组,该数组中除了一个数字只出现一次以外,剩余的数字都会出现两次,返回只出现一次的数字

注意:你的算法应该只有线性的运行时间复杂度。你可以不用额外空间实现它么?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

1:利用list.pop()+list.remove()实现(时间复杂度较高,且申请了额外的空间)

def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        while len(nums)!=1:
            lastCha = nums.pop()
            if lastCha in nums:
                nums.remove(lastCha)
            else:
                return lastCha
        return nums[0]

2:^位运算,时间复杂度最小(参考他人代码)

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

3:利用list.sort()

def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        for i in range(0,len(nums)-1,2):
            if nums[i] != nums[i+1]:
                return nums[i]
        return nums[-1]

4:错误:超出时间限制

def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        index = 0
        while index<len(nums):
            if nums[index] not in nums[:index] and nums[index] not in nums[index+1:]:
                return nums[index]
            index += 1

算法题来自:https://leetcode-cn.com/problems/single-number/description/

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值