How to find N longest lines in a text file and print them to stdout?

有些话、适合烂在心里 提交于 2019-12-05 08:49:46
  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.
    
  2. it could also be done in O(n) using Select(N) (which selects the Nth number) followed by partition around the Nth number (which arranges all the with size larger or equal to the Nth number to one side of it).

       i = Select(lines, N)
       partition(lines, i)
       for i to size(lines):
             print to stdout: lines[i]
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!