LeetCode-Python-137. 只出现一次的数字 II

654 篇文章 23 订阅

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

说明:

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

示例 1:

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

输入: [0,1,0,1,0,1,99]
输出: 99

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

第一种思路:

用哈希表记录每个元素出现的频率。

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        from collections import defaultdict
        record = defaultdict(int)
        
        for i, x in enumerate(nums):
            record[x] += 1
        
        for key, val in record.items():
            if val == 1:
                return key

第二种思路:

转成set,用和的差值找到只出现了一次的元素。

因为理论上如果所有数字都出现了三次,那么sum(nums) == 3 *sum(set(nums))

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return (3 * sum(set(nums)) - sum(nums)) // 2

第三种思路:

bitmap法,

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = 0
        for i in range(32): #32个位每个位循环
            bitnum = 0
            bit = 1 << i #当前是第i位
            
            for num in nums:
                if num & bit:
                    bitnum += 1
            if bitnum % 3 != 0: #说明当前位在要找的数里为1
                res ^= bit
        return res

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值