题目
原文:
You have an array with all the numbers from 1 to N, where N is at most 32,000. The array may have duplicate entries and you do not know what N is.
With only 4KB of memory available, how would you print all duplicate elements in the array?
译文:
你有一个存有1到N所有数据的数组,N最大为32,000。这个数组可能有重复的元素,你并不知道N是什么。仅仅4kb的内存可用,怎样打印出这个数组中所有重复的元素。
解答
4kb的内存有4*1024*8=32768>32000,所以可以用Bit Map来处理,代码如下:
class Q12_4{ public static void print_duplicates(int[] a,int n,int bitsize){ BitMap bm=new BitMap(bitsize); for(int i=0;i<n;++i){ if(bm.get(a[i]-1)) System.out.println(a[i]); else bm.set(a[i]-1); } } public static void main(String[] args){ int a[] = { 1,2,3,4,5,32000,7,8,9,10,11,1,2,13,15,16,32000,11,5,8 }; print_duplicates(a,20,32000); } } class BitMap{ public int[] bits; public BitMap(int size){ bits=new int[size]; } public boolean get(int pos){ return (bits[pos/32]&(1<<(pos&0x1f)))!=0; } public void set(int pos){ bits[pos/32]|=(1<<(pos&0x1f)); } }
Cracking the coding interview--Q12.4,布布扣,bubuko.com
Cracking the coding interview--Q12.4
原文:http://blog.csdn.net/navyifanr/article/details/21334663