137. Single Number II

137. Single Number II

Medium

2636405Add to ListShare

Given an integer array nums where every element appears three times except for one, which appears exactly onceFind the single element and return it.

You must implement a solution with a linear runtime complexity and use only constant extra space.

 

Example 1:

Input: nums = [2,2,3,2]
Output: 3

Example 2:

Input: nums = [0,1,0,1,0,1,99]
Output: 99

 

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • Each element in nums appears exactly three times except for one element which appears once.

 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        """
        assert Solution().singleNumber([-2, -2, 1, 1, 4, 1, 4, 4, -4, -2]) == -4
        assert Solution().singleNumber([2, 2, 3, 2]) == 3
        assert Solution().singleNumber([0, 1, 0, 1, 0, 1, 99]) == 99

        解题思路1:同【136	Single Number】解法,用个map存
        时间复杂度:O(n),空间复杂度:O(n)
        解题思路2:用个32位数组count[32],记录各位出现的次数,找出所有出现1次的位组成就是结果
        补码 = 原码除符号位按位取反,末位+1
        注意处理负数,因为负数在计算机里是以补码的形式保存,-1的补码是11111111111...,不断右移还是-1
        时间复杂度:O(n),空间复杂度:O(1)
        """
        if len(nums) == 1:
            return nums[0]
        count = [0] * 32
        sign = 0
        for num in nums:
            sign += 1 if num >= 0 else 0
            positive = abs(num)
            for i in range(0, 32):
                count[i] += (positive >> i) & 1
                count[i] %= 3
        result = 0
        for i in range(0, 32):
            result += (count[i] << i)
        return result if (sign % 3 != 0) else -result

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值