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/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82525985
今日推荐