Posted on 2023-07-05 00:36
Uriel 閱讀(33)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code 、
位運算
一個數(shù)列,有一個數(shù)只出現(xiàn)1次,其他所有數(shù)都出現(xiàn)3次,找出出現(xiàn)1次的數(shù)
思路見9年前C++版本的記錄->http://www.shnenglu.com/Uriel/articles/205406.html
Python版 (注意處理負(fù)數(shù)的情況,看了Discussion才意識到)
1 #137
2 #Runtime: 83 ms (Beats 39.2%)
3 #Memory: 14.8 MB (Beats 89.66%)
4
5 class Solution(object):
6 def singleNumber(self, nums):
7 """
8 :type nums: List[int]
9 :rtype: int
10 """
11 ans = 0
12 for i in range(32):
13 cnt = 0
14 for m in nums:
15 t = (m >> i) & 1
16 cnt += t
17 cnt %= 3
18 if cnt and i == 31:
19 ans -= 1 << 31
20 else:
21 ans |= cnt << i
22 return ans