File tree 3 files changed +67
-0
lines changed
solution/137.Single Number II
3 files changed +67
-0
lines changed Original file line number Diff line number Diff line change @@ -61,6 +61,7 @@ Complete solutions to Leetcode problems, updated daily.
61
61
| 102 | [ Binary Tree Level Order Traversal] ( https://github.com/doocs/leetcode/tree/master/solution/102.Binary%20Tree%20Level%20Order%20Traversal ) | ` Tree ` , ` Breadth-first Search ` |
62
62
| 127 | [ Word Ladder] ( https://github.com/doocs/leetcode/tree/master/solution/127.Word%20Ladder ) | ` Breadth-first Search ` |
63
63
| 130 | [ Surrounded Regions] ( https://github.com/doocs/leetcode/tree/master/solution/130.Surrounded%20Regions ) | ` Depth-first Search ` , ` Breadth-first Search ` , ` Union Find ` |
64
+ | 137 | [ Single Number II] ( https://github.com/doocs/leetcode/tree/master/solution/137.Single%20Number%20II ) | ` Bit Manipulation ` |
64
65
| 144 | [ Binary Tree Preorder Traversal] ( https://github.com/doocs/leetcode/tree/master/solution/144.Binary%20Tree%20Preorder%20Traversal ) | ` Stack ` , ` Tree ` |
65
66
| 150 | [ Evaluate Reverse Polish Notation] ( https://github.com/doocs/leetcode/tree/master/solution/150.Evaluate%20Reverse%20Polish%20Notation ) | ` Stack ` |
66
67
| 153 | [ Find Minimum in Rotated Sorted Array] ( https://github.com/doocs/leetcode/tree/master/solution/153.Find%20Minimum%20in%20Rotated%20Sorted%20Array ) | ` Array ` , ` Binary Search ` |
Original file line number Diff line number Diff line change
1
+ ## 只出现一次的数字 II
2
+
3
+ ### 题目描述
4
+ 给定一个** 非空** 整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
5
+
6
+ 说明:
7
+
8
+ 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
9
+
10
+ ** 示例 1:**
11
+ ```
12
+ 输入: [2,2,3,2]
13
+ 输出: 3
14
+ ```
15
+
16
+ ** 示例 2:**
17
+ ```
18
+ 输入: [0,1,0,1,0,1,99]
19
+ 输出: 99
20
+ ```
21
+
22
+ ### 解法
23
+ 遍历数组元素,对于每一个元素,获得二进制位(0/1),累加到 bits 数组中,这样下来,出现三次的元素,bits 数组上的值一定能被 3 整除;找出不能被 3 整除的位,计算出实际的十进制数即可。
24
+
25
+ ``` java
26
+ class Solution {
27
+ public int singleNumber (int [] nums ) {
28
+ int [] bits = new int [32 ];
29
+ int n = nums. length;
30
+ for (int i = 0 ; i < n; ++ i) {
31
+ for (int j = 0 ; j < 32 ; ++ j) {
32
+ bits[j] += ((nums[i] >> j) & 1 );
33
+ }
34
+ }
35
+
36
+ int res = 0 ;
37
+ for (int i = 0 ; i < 32 ; ++ i) {
38
+ if (bits[i] % 3 != 0 ) {
39
+ res += (1 << i);
40
+ }
41
+ }
42
+ return res;
43
+
44
+ }
45
+ }
46
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int singleNumber (int [] nums ) {
3
+ int [] bits = new int [32 ];
4
+ int n = nums .length ;
5
+ for (int i = 0 ; i < n ; ++i ) {
6
+ for (int j = 0 ; j < 32 ; ++j ) {
7
+ bits [j ] += ((nums [i ] >> j ) & 1 );
8
+ }
9
+ }
10
+
11
+ int res = 0 ;
12
+ for (int i = 0 ; i < 32 ; ++i ) {
13
+ if (bits [i ] % 3 != 0 ) {
14
+ res += (1 << i );
15
+ }
16
+ }
17
+ return res ;
18
+
19
+ }
20
+ }
You can’t perform that action at this time.
0 commit comments