-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path137. Single Number II (Bit Manipulation)
More file actions
59 lines (49 loc) · 2.12 KB
/
137. Single Number II (Bit Manipulation)
File metadata and controls
59 lines (49 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
137. Single Number II
Medium
751
244
Favorite
Share
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
Solution:------------------------------------ Bit Manipulation ------- https://www.youtube.com/watch?v=puXcQpwgcD0
--------------------------------------------- O(n) T, O(1) S
'''
& : and
| : or
^ : XOR, same -> 0, different -> 1
~ : 0 -> 1, 1 -> 0
<<: 左移
>>: 右移
'''
class Solution(object):
def singleNumber(self, nums):
if not nums:
return None
res = 0
for i in range(32):
counter = 0
for num in nums:
counter += (num >> i) & 1 # >> : 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数
# num >> i is an integer, we use & 1 to get the binary_representation[i]
rem = counter % 3 # take the remainder with 3 because every element appears three times except for one
# So, if every element appears five times except for one, we use % 5
if i == 31 and rem: # Must handle the negative case, and IMPORTANT !!!!!!! we must let rem = counter % 3
# before we can handle the negative case, otherwise will bring error !!!!!
# because the rem is meaningless before we do % 3,
# so the negative case cannot be proceeded before we get the meaningful rem
res -= 1 << 31 # 1 << 31 = 2147483648
else:
res |= rem << i # use |= to update the res in binary form everytime
return res
"""
:type nums: List[int]
:rtype: int
"""