File tree Expand file tree Collapse file tree 2 files changed +50
-1
lines changed Expand file tree Collapse file tree 2 files changed +50
-1
lines changed Original file line number Diff line number Diff line change 153
153
215. 数组中的第K个最大元素(快速排序,堆排序)
154
154
239. 滑动窗口最大值(单调递减双端队列)
155
155
283. 移动零(双指针)
156
- 287. 寻找重复数(哈希表,快慢指针,二分查找)
156
+ 287. 寻找重复数(哈希表,快慢指针,二分查找,位运算 )
157
157
303. 区域和检索 - 数组不可变(前缀和)
158
158
304. 二维区域和检索 - 矩阵不可变(前缀和)
159
159
406. 根据身高重建队列(二维数组排序)
173
173
174
174
175
175
九、位运算
176
+ 287. 寻找重复数
176
177
338. 比特位计数
177
178
461. 汉明距离
178
179
Original file line number Diff line number Diff line change @@ -92,4 +92,52 @@ public int findDuplicate(int[] nums) {
92
92
}
93
93
return left ;
94
94
}
95
+ }
96
+
97
+
98
+ /*
99
+ 位运算:将 原数组 与 [1,n]数字 转化成二进制后,统计对应每一位1的个数,原数组比范围数组 位上多出来的1 是重复元素位上的1,找到重复元素所有位上的1后 转化得到重复元素值
100
+ nums = [1,3,4,2,2]
101
+
102
+ 1 3 4 2 2 写成二进制
103
+ 1 [0 0 1]
104
+ 3 [0 1 1]
105
+ 4 [1 0 0]
106
+ 2 [0 1 0]
107
+ 2 [0 1 0]
108
+ x 1 3 2
109
+
110
+ 把 1 到 n,也就是 1 2 3 4 也写成二进制
111
+ 1 [0 0 1]
112
+ 2 [0 1 0]
113
+ 3 [0 1 1]
114
+ 4 [1 0 0]
115
+ y 1 2 2
116
+
117
+ res 0 1 0
118
+ */
119
+ class Solution {
120
+ public int findDuplicate (int [] nums ) {
121
+ int res = 0 , n = nums .length ;
122
+ int maxBit = 31 ;
123
+ while (((n - 1 ) >> maxBit ) == 0 ) {
124
+ maxBit --;
125
+ }
126
+ for (int i = 0 ; i <= maxBit ; i ++) {
127
+ int x = 0 , y = 0 ;
128
+ int mask = (1 << i );
129
+ for (int j = 0 ; j < n ; j ++) {
130
+ if ((nums [j ] & mask ) > 0 ) {
131
+ x ++;
132
+ }
133
+ if ((j & mask ) > 0 ) {
134
+ y ++;
135
+ }
136
+ }
137
+ if (x > y ) {
138
+ res |= mask ;
139
+ }
140
+ }
141
+ return res ;
142
+ }
95
143
}
You can’t perform that action at this time.
0 commit comments