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

前端 未结 30 2200
深忆病人
深忆病人 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:51

    Two options:

    (1) Heap (priorityQueue)

    Maintain a min-heap with size of 100. Traverse the array. Once the element is smaller than first element in heap, replace it.

    InSERT ELEMENT INTO HEAP: O(log100)
    compare the first element: O(1)
    There are n elements in the array, so the total would be O(nlog100), which is O(n)
    

    (2) Map-reduce model.

    This is very similar to word count example in hadoop. Map job: count every element's frequency or times appeared. Reduce: Get top K element.

    Usually, I would give the recruiter two answers. Give them whatever they like. Of course, map reduce coding would be labor-some because you have to know every exact parameters. No harm to practice it. Good Luck.

提交回复
热议问题