大数据量(10亿)的整数看是否有重复的

使用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);
		}
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值