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

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

    This question would be answered with N log(100) complexity (instead of N log N) with just one line of C++ code.

     std::vector myvector = ...; // Define your 1 billion numbers. 
                                     // Assumed integer just for concreteness 
     std::partial_sort (myvector.begin(), myvector.begin()+100, myvector.end());
    

    The final answer would be a vector where the first 100 elements are guaranteed to be the 100 biggest numbers of you array while the remaining elements are unordered

    C++ STL (standard library) is quite handy for this kind of problems.

    Note: I am not saying that this is the optimal solution, but it would have saved your interview.

提交回复
热议问题