How to find N longest lines in a text file and print them to stdout?
问题 The first line contains the value of the number 'N' followed by multiple lines. I could solve it in order of n^2 algorithm. Can someone suggest a better one? 回答1: You can use a minimum-heap and do it in O(n*(log(N))): heap = new Min-Heap(N) foreach line in text: if length(line) > heap.min(): heap.pop() heap.insert(line) foreach line in heap: print to stdout: line. it could also be done in O(n) using Select(N) (which selects the Nth number) followed by partition around the Nth number (which