使用BitMap:用位存储每个数,比如1,2,3....,31,32这32个数那么可以用一个32位的int值state来存,1存到int的最低位bit位上,32则存到最高位的bit位上;比如检测5是否存在,那么看int值得第5位是否是1,也就是state>>(5-1) & 1,看是不是为1,如果为1,说明5存在,否则不存在,同时将5加进去。
java实例代码:
package cn.wzy.Collection;
import java.util.HashMap;
import java.util.Random;
public class BitMap {
static int[] map = new int[500];
static boolean add(int now) {
int index = now / 32;//得到存储数
int bit = now % 32;//得到第几位
if (bit == 0) {
index--;
bit = 32;
}
bit--;
boolean res = (map[index] >> bit & 1) == 1;
map[index] = map[index] | (1 << bit);
return res;
}
public static void main(String[] args) {
Random random = new Random();
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < 5000; i++) {
int num = random.nextInt(32 * 500) + 1;
System.out.println("the answer is : " + (add(num) == hashMap.containsKey(num)));
hashMap.put(num,1);
}
}
}