package common; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.Random; public class BitMapDemo { /** * 有1千万个随机数,随机数的范围在1到1亿之间。现在要求写出一种算法,将1到1亿之间没有在随机数中的数求出来? * @author Administrator * */ public static void main(String[] args) { Random random = new Random(); int bitLen = 10000000,count=0; List<Integer> list = new ArrayList<>(); for (int i = 0; i < bitLen; i++) { int randomResult = random.nextInt(bitLen); list.add(randomResult); } if(bitLen<100){ System.out.println("产生的随机数有"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } BitSet bitSet = new BitSet(bitLen); //构造方法传入的是位数的个数 for (int i = 0; i < bitLen; i++) { bitSet.set(list.get(i)); } for (int i = 0; i < bitLen; i++) { if (!bitSet.get(i)) { //System.out.println(i); count++; } } System.out.println("0~"+bitLen+"不在上述随机数中有" + count+"个"); //返回bitSet实际占用的字节个数 由于bitSet基于long数组,sizeof(long) = 64 > 10 所以只需要一个long元素 System.out.println("bitSet size="+bitSet.size()); //返回实用的long元素个数 System.out.println("bitSet long size="+bitSet.size()/64); //返回位数的逻辑大小 System.out.println("bitSet length="+bitSet.length()); //返回位数值为true的个数 System.out.println("bitSet cardinality="+bitSet.cardinality()); // BitSetNotIncount = bitSet.length()-bitSet.cardinality(); System.out.println("count="+count+",BitSetNotIncount="+(bitSet.length()-bitSet.cardinality())); } }