Repository navigation
Expand file tree
/
Copy pathBitMap.java
More file actions
72 lines (63 loc) · 2.16 KB
/
Copy pathBitMap.java
File metadata and controls
72 lines (63 loc) · 2.16 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
60
61
62
63
64
65
66
67
68
69
70
71
72
package Novice_class;
import java.util.HashSet;
// 实现位图
public class BitMap {
private long[] bits;
public BitMap(int max) {
// max + 64 -> 当max == 63时,我们需要1个空间,当max == 0时我们需要1个空间
bits = new long[(max + 64) >> 6];
}
public void add(int num) {
/*
// 属于哪个数组的下标
int flg1 = num >> 6;
// 属于当前数组下标下的哪个位置
int flg2 = num & 63;
bits[flg1] = (1L << flg2) | bits[flg1];
*/
bits[num >> 6] |= (1L << (num & 63));
// bits[num >> 6] |= (1L << (num & 63));
}
public void delete(int num) {
/**
* int flg1 = num >> 6;
* int flg2 = num & 63;
* bits[flg1] = bits[flg1] & ~(1L << flg2);
*/
bits[num >> 6] &= ~(1L << (num & 63));
// bits[num >> 6] &= ~(1L << (num & 63));
}
public boolean contains(int num) {
return (bits[num >> 6] & (1L << (num & 63))) != 0;
// return (bits[num >> 6] & (1L << (num & 63))) != 0;
}
public static void main(String[] args) {
int testTime = 1000000;
int maxValue = 1000000;
BitMap bitMap = new BitMap(maxValue);
HashSet<Integer> hashSet = new HashSet<>();
System.out.println("测试开始");
for (int i = 0; i < testTime; i++) {
int value = (int)(Math.random()*maxValue);
double decide = Math.random();
if(decide < 0.333) {
bitMap.add(value);
hashSet.add(value);
}else if(decide < 0.666) {
bitMap.delete(value);
hashSet.remove(value);
}else {
if(bitMap.contains(value) != hashSet.contains(value)) {
System.out.println("OOPS");
break;
}
}
}
for (int i = 0; i < maxValue; i++) {
if(bitMap.contains(i) != hashSet.contains(i)) {
System.out.println("OOPS");
}
}
System.out.println("测试结束");
}
}