一個(gè)數(shù)列,有一個(gè)數(shù)只出現(xiàn)1次,其他所有數(shù)都出現(xiàn)3次,找出出現(xiàn)1次的數(shù)
思路見(jiàn)9年前C++版本的記錄->http://m.shnenglu.com/Uriel/articles/205406.html
Python版 (注意處理負(fù)數(shù)的情況,看了Discussion才意識(shí)到)
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