44
44
45
45
<!-- 这里可写通用的实现逻辑 -->
46
46
47
- 统计所有数字每个位中 1 出现的次数,对于某个位,1 出现的次数一定是 3 的倍数 +1 或 0。对这个数 %3 得到的结果就是那个出现一次的数字在该位上的值。
47
+ ** 方法一:位运算**
48
+
49
+ 我们可以统计所有数字中每个位上出现的 $1$ 的个数,然后对 $3$ 取模。如果某一位上的出现的 $1$ 的个数无法被 $3$ 整除,说明只出现一次的数字在该位上是 $1$,否则是 $0$。
50
+
51
+ 时间复杂度 $O(n \times \log M)$,其中 $n$ 是数组 $nums$ 的长度,而 $M$ 是数组中元素的最大值。空间复杂度 $O(1)$。
48
52
49
53
<!-- tabs:start -->
50
54
@@ -57,7 +61,7 @@ class Solution:
57
61
def singleNumber (self , nums : List[int ]) -> int :
58
62
ans = 0
59
63
for i in range (32 ):
60
- cnt = sum (num >> i & 1 for num in nums)
64
+ cnt = sum (x >> i & 1 for x in nums)
61
65
if cnt % 3 :
62
66
if i == 31 :
63
67
ans -= 1 << i
@@ -74,10 +78,10 @@ class Solution:
74
78
class Solution {
75
79
public int singleNumber (int [] nums ) {
76
80
int ans = 0 ;
77
- for (int i = 0 ; i < 32 ; i ++ ) {
81
+ for (int i = 0 ; i < 32 ; ++ i ) {
78
82
int cnt = 0 ;
79
- for (int num : nums) {
80
- cnt += num >> i & 1 ;
83
+ for (int x : nums) {
84
+ cnt += x >> i & 1 ;
81
85
}
82
86
cnt %= 3 ;
83
87
ans |= cnt << i;
@@ -87,25 +91,6 @@ class Solution {
87
91
}
88
92
```
89
93
90
- ### ** Go**
91
-
92
- 需要注意 Golang 中的 ` int ` 在 64 位平台上相当于 ` int64 `
93
-
94
- ``` go
95
- func singleNumber (nums []int ) int {
96
- ans := int32 (0 )
97
- for i := 0 ; i < 32 ; i++ {
98
- cnt := int32 (0 )
99
- for _ , num := range nums {
100
- cnt += int32 (num) >> i & 1
101
- }
102
- cnt %= 3
103
- ans |= cnt << i
104
- }
105
- return int (ans)
106
- }
107
- ```
108
-
109
94
### ** C++**
110
95
111
96
``` cpp
@@ -115,8 +100,8 @@ public:
115
100
int ans = 0;
116
101
for (int i = 0; i < 32; ++i) {
117
102
int cnt = 0;
118
- for (int num : nums) {
119
- cnt += ((num >> i) & 1) ;
103
+ for (int x : nums) {
104
+ cnt += (x >> i) & 1;
120
105
}
121
106
cnt %= 3;
122
107
ans |= cnt << i;
@@ -126,6 +111,40 @@ public:
126
111
};
127
112
```
128
113
114
+ ### **Go**
115
+
116
+ ```go
117
+ func singleNumber(nums []int) int {
118
+ var ans int32
119
+ for i := 0; i < 32; i++ {
120
+ cnt := 0
121
+ for _, x := range nums {
122
+ cnt += x >> i & 1
123
+ }
124
+ cnt %= 3
125
+ ans |= int32(cnt) << i
126
+ }
127
+ return int(ans)
128
+ }
129
+ ```
130
+
131
+ ### ** TypeScript**
132
+
133
+ ``` ts
134
+ function singleNumber(nums : number []): number {
135
+ let ans = 0 ;
136
+ for (let i = 0 ; i < 32 ; ++ i ) {
137
+ let cnt = 0 ;
138
+ for (const x of nums ) {
139
+ cnt += (x >> i ) & 1 ;
140
+ }
141
+ cnt %= 3 ;
142
+ ans |= cnt << i ;
143
+ }
144
+ return ans ;
145
+ }
146
+ ```
147
+
129
148
### ** ...**
130
149
131
150
```
0 commit comments