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

前端 未结 30 2208
深忆病人
深忆病人 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条回答
  •  旧时难觅i
    2020-11-29 14:49

    Time ~ O(100 * N)
    Space ~ O(100 + N)
    
    1. Create an empty list of 100 empty slot

    2. For every number in input-list:

      • If the number is smaller than the first one, skip

      • Otherwise replace it with this number

      • Then, push the number through adjacent swap; until it's smaller than the next one

    3. Return the list


    Note: if the log(input-list.size) + c < 100, then the optimal way is to sort the input-list, then split first 100 items.

提交回复
热议问题