当前位置:   article > 正文

Leetcode 137. Single Number II

Leetcode 137. Single Number II

Problem

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

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

Algorithm

Using trinary solving, all numbers are converted to trinary. Adding each digit and taking the remainder of the pair of three, sum them up to the result. A special treatment is required when taking the remainder of a negative number. To reduce space, scanning by digit.

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        sLen = len(nums)
        p_cnt, n_cnt = 0, 0
        for i in range(sLen):
            p_cnt += (nums[i] > 0)
            n_cnt += (nums[i] < 0)
        
        if p_cnt % 3 == 0:
            if n_cnt % 3 == 0:
                return 0
            else:
                ans = 0
                base = 1
                for k in range(20):
                    val = 0
                    for i in range(sLen):
                        if nums[i] < 0:
                            val += ((-1-nums[i]) // base) % 3
                    ans += val % 3 * base
                    base *= 3
                return -1-ans
        else:
            ans = 0
            base = 1
            for k in range(20):
                val = 0
                for i in range(sLen):
                    if nums[i] > 0:
                        val += nums[i] // base % 3
                ans += val % 3 * base
                base *= 3
            return ans
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号