給你一個整數(shù)數(shù)組 nums ,除某個元素僅出現(xiàn) 一次 外,其余每個元素都恰出現(xiàn) 三次 。請你找出并返回那個只出現(xiàn)了一次的元素。
你必須設計并實現(xiàn)線性時間復雜度的算法且使用常數(shù)級空間來解決此問題。
示例 1:
輸入:nums = [2,2,3,2]
輸出:3
示例 2:
輸入:nums = [0,1,0,1,0,1,99]
輸出:99文章來源:http://www.zghlxwxcb.cn/news/detail-701662.html
提示:
1 <= nums.length <= 3 * 10^4
-2^31 <= nums[i] <= 2^31 - 1
nums 中,除某個元素僅出現(xiàn) 一次 外,其余每個元素都恰出現(xiàn) 三次
題目鏈接
思路,每個數(shù)都是 32 bit, 統(tǒng)計每個 bit 所有數(shù)在該 bit 位 1個個數(shù),設該值為 sum, 若 sum%3 != 0, 說明僅出現(xiàn)一次的元素的該 bit 為 1, 循環(huán) 32次就能計算出來了。文章來源地址http://www.zghlxwxcb.cn/news/detail-701662.html
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res, level = 0, 0
while level < 32:
sum = 0
for x in nums:
sum += (x >> level)&1
if sum % 3 != 0:
if level == 31: ### 注意: python 無符號數(shù), 最高位代表符號
res -= (1 << level)
else:
res += (1 << level)
level += 1
return res
到了這里,關于leetcode 137. 只出現(xiàn)一次的數(shù)字 II的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!