LeetCode 137 Single Number II (Python)

Posted by 小明MaxMing on June 22, 2020

题目

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

解题思路

位运算做法请参考博客

代码

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return (3 * sum(set(nums)) - sum(nums)) // 2
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        res = 0
        for i in range(32):
            ct = 0
            for n in nums:
                ct += (n >> i) & 1
            res |= (ct % 3) << i
        return res - 2**32 if res >> 31 & 1 else res
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        low = high = 0;
        for n in nums:
            low = (low ^ n) & ~high;
            high = (high ^ n) & ~low;
        return low

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅