/**
* Function: Given an array containing 1 to n integers, n maximum is 32000, the array may contain duplicate values, and the value of n is variable.
* If only 4KB of memory is available, how to print all the duplicated elements in the array.
*/
/** * Idea: 4KB up to 8*4*2^10 a bit. Bigger than 32000. Creates a bit vector that contains 32,000 bits, where each bit represents an integer. * Duplicate elements are encountered and printed out. * @param array */public static void Checkduplicates (int[] array) {BitSet bs=new BitSet (32000); for (int i=0;i< array.length;i++) {int Num=array[i];int num0=num-1;//bitser starting from 0, number starting from 1 if (Bs.get (NUM0)) {System.out.println (num);// Print original value}else{bs.set (NUM0);//Deposit to NUM0}}}
Class bitset{int[] bitset;public BitSet (int size) {bitset=new int[size>>5];//divided by 32}public boolean get (int pos) {int wordnumber=pos>>5;//divided by 32int bitnumber=pos& (0x1F),//divided by 32 to take the remainder return (bitset[wordnumber]& (1<< Bitnumber))!=0;} public void set (int pos) {int wordnumber=pos>>5;//divided by 32int bitnumber=pos& (0x1F);//divided by 32 to take the remainder Bitset[wordnumber] |= (1<<bitnumber);}}
Note: You can also refer to the Java built-in Bitset class.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.10 Extensibility and Storage Limitations (iii)-How to print all duplicate elements in an array if only 4KB of memory is available