9.10 Extensibility and Storage Limitations (iii)-How to print all duplicate elements in an array if only 4KB of memory is available

Source: Internet
Author: User
Tags bitset

/**
* 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.