Posted on 2023-07-05 00:36
Uriel 閱讀(33)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code 、
位運算
一個數列,有一個數只出現1次,其他所有數都出現3次,找出出現1次的數
思路見9年前C++版本的記錄->http://www.shnenglu.com/Uriel/articles/205406.html
Python版 (注意處理負數的情況,看了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