It is an interview question.
Given a text file, each line includes : shipment ID , UPC code , quantity
Find the 10 largest quantity lines.
My solutions :
By c++
make a min heap (with size 10) with quantity as compare object.
Read each entry as a struct with field { shipment ID, UPC code, quantity }
Compare it with the top element of the 10-element min-heap,
if > replace the top element with it, else read the next element.
It is O(n lg n).
Space O(1).
Better solutions ?
thanks
Side note: Your time cost is actually O(n), since the per-element insertion time is a constant (O(log 10)).
The basic idea is sound — you won’t do better than O(n) in terms of cost — but rather than rolling your own heap, use
std::priority_queue.