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

前端 未结 30 2130
深忆病人
深忆病人 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 15:02

    THe complexity is O(N)

    First create an array of 100 ints initialiaze the first element of this array as the first element of the N values, keep track of the index of the current element with a another variable, call it CurrentBig

    Iterate though the N values

    if N[i] > M[CurrentBig] {
    
    M[CurrentBig]=N[i]; ( overwrite the current value with the newly found larger number)
    
    CurrentBig++;      ( go to the next position in the M array)
    
    CurrentBig %= 100; ( modulo arithmetic saves you from using lists/hashes etc.)
    
    M[CurrentBig]=N[i];    ( pick up the current value again to use it for the next Iteration of the N array)
    
    } 
    

    when done , print the M array from CurrentBig 100 times modulo 100 :-) For the student: make sure that the last line of the code does not trump valid data right before the code exits

提交回复
热议问题