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

你可能感兴趣的:(Leetcode,解题报告,leetcode,算法,职场和发展)