Write a program to find 100 largest numbers out of an array of 1 billion numbers

前端 未结 30 2203
深忆病人
深忆病人 2020-11-29 14:04

I recently attended an interview where I was asked \"write a program to find 100 largest numbers out of an array of 1 billion numbers.\"

I was only able to give a br

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 14:55

    You can use Quick select algorithm to find the number at the(by order) index [billion-101] and then iterate over the numbers and to find the numbers that biger from that number.

    array={...the billion numbers...} 
    result[100];
    
    pivot=QuickSelect(array,billion-101);//O(N)
    
    for(i=0;i=pivot)
          result.add(array[i]);
    

    This algorithm Time is: 2 X O(N) = O(N) (Average case performance)

    The second option like Thomas Jungblut suggest is:

    Use Heap building the MAX heap will take O(N),then the top 100 max numbers will be in the top of the Heap, all you need is to get them out from the heap(100 X O(Log(N)).

    This algorithm Time is:O(N) + 100 X O(Log(N)) = O(N)

提交回复
热议问题