用bitmap实现中位数的算法[ZT]

http://blog.csdn.net/hfahe/archive/2010/05/07/5567259.aspx

 

常见面试题之一:50亿个整数,内存限制为1G,找出中位数。

50亿个整数用bitmap来存储的话,大约150M的空间就足够了。

下面是具体的算法,用PHP实现。

view plaincopy to clipboardprint?

  1. define("MASK", 0x1f); 
  2. $source = array(1, 74, 4, 256, 1024, 110, 111, 112, 123, 112, 100); 
  3. $array = array(); 
  4. $count = 0; 
  5. foreach($source as $num) { 
  6.     set($num); // add to bit map
  7. $count = intval($count >> 1) + 1; // cal middle number
  8. for($i = 0;;$i++) { // travel the bit map and find the middle number
  9. $num = $array[$i]; 
  10. if(!$num) { 
  11. continue; 
  12.     } 
  13. $sum = 0; 
  14. while($num) { 
  15. if($num & 0x1) { 
  16. if(!--$count) { 
  17. echo ($i << 5) + $sum; 
  18. exit;        
  19.             } 
  20.         } 
  21. $num >>= 1; 
  22. $sum++; 
  23.     } 
  24. /*
  25. * set number to bit map
  26. */
  27. function set($i) { 
  28. global $array; 
  29. global $count; 
  30. $temp = (1 << ($i & MASK)); 
  31. $array[$i >> 5] |= $temp; 
  32. if($temp) { 
  33. $count++; 
  34.     } 
posted @ 2010-08-29 16:38  donj  阅读(727)  评论(0编辑  收藏  举报