leetcode136 只出现一次的数字(python3)

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

说明:

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

示例 1:

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

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


直接上代码(5种解题方法):

class Solution:
    def singleNumber(self, nums):

# 超时
        while True:
            i = nums[0]
            nums.pop(0)
            if nums.count(i) == 0:
                return i
            else:
                nums.remove(i)

# 没超时,但是1700+
        while True:
            i = nums[0]
            nums.pop(0)
            try:
                nums.remove(i)
            except:
                return i

# 神作 按位异或,总会把相同的去掉
        a = 0
        for i in nums:
            a = a ^ i
        return a

# 最简洁
        return sum(set(nums)) * 2 - sum(nums)


# collection 库
	    import collections
	    j = collections.Counter(nums)
	    for i in j:
	        if j[i] == 1:
	            return i

collections.Counter() 可以将字符串,列表,元组,转化成字典,并按照字符:出现次数的键值对的形式储存

猜你喜欢

转载自blog.csdn.net/weixin_43944749/article/details/85110516