-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (62 loc) · 1.48 KB
/
index.js
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
function getBitIndexAndValue(n) {
return {
index: n >> 5,
flag: 1 << (n & 0x1f)
};
}
function isNumber(num) {
return typeof num === 'number';
}
/**
* BitMap
*/
class BitMap {
constructor(data = []) {
this._data = {};
if (Array.isArray(data) && data.length > 0) {
const that = this;
data.forEach(function (item) {
if (isNumber(item)) {
that.push(item);
}
});
}
}
push(n) {
const {index, flag} = getBitIndexAndValue(n);
this._data[index] || (this._data[index] = 0);
this._data[index] |= flag;
return this;
}
isExist(n) {
if (!isNumber(n)) {
return false;
}
const {index, flag} = getBitIndexAndValue(n);
if (!this._data[index]) {
return false;
}
return Boolean(this._data[index] & flag);
}
clear() {
this._data = {};
return this;
}
toString() {
const that = this;
return Object.keys(this._data).map(function (key) {
return `${(that._data[key]).toString(2)}`;
}).join(',');
}
}
export default BitMap;
/**
* todo 2-Bitmap
*/
/**
* 将bit-map扩展一下,采用2-Bitmap
* (每个数分配2bit,00表示不存在,01表示出现一次,10表示多次,11无意义)进行,
* 共需内存2^32 * 2 bit=1 GB内存,还可以接受。然后扫描这2.5亿个整数,
* 查看Bitmap中相对应位,如果是00变01,01变10,10保持不变。所描完事后,查看bitmap,
* 把对应位是01的整数输出即可
*/