Created
August 8, 2014 06:07
-
-
Save KodeSeeker/ee68c9d6fc2f311664f4 to your computer and use it in GitHub Desktop.
Find the number missing in a input file of 4 billion distinct integers. You have 1GB of memory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Idea is to use a bitfield to compactly represent each number | |
| * Ctci Pg 346. | |
| * | |
| **/ | |
| public int missingNumber() | |
| { | |
| long numofInts= INTEGER.MAX_VALUE+1; | |
| boolean[] bitField= new new boolean [numofInts/8]; | |
| for(int i: inStream.nextInt()) | |
| { | |
| bitField[i/8] | = 1 << (i%8);//sets the ith bit in the ith boolean. | |
| } | |
| } | |
| //check fo missing num | |
| for (int i=0;i<bitField.length;i++) | |
| { | |
| //check for each bit | |
| for(int j=0 j< 8;j++) | |
| { | |
| if(bitField[i] & (1<<j)===0) | |
| { | |
| System.out.print( (i*8)+j); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment