Algorithm to find 100 closest stars to the origin

后端 未结 5 827
花落未央
花落未央 2021-01-31 11:34

First let me phrase the proper question:

Q: There is a file containing more than a million points (x,y) each of which represents a star. There is a planet earth

5条回答
  •  眼角桃花
    2021-01-31 12:18

    To elaborate on the MaxHeap solution you would build a max-heap with the first k elements from the file ( k = 100 in this case ).

    The key for the max-heap would be its distance from Earth (a,b). Distance between 2 points on a 2d plane can be calculated using:

    dist = (x1,y1) to (x2,y2) = square_root((x2 - x1)^2 + (y2 - y1)^2); 
    

    This would take O(k) time to construct. For every subsequent element from k to n. ie (n - k) elements you need to fetch its distance from earth and compare it with the top of max-heap. If the new element to be inserted is closer to earth than the top of the max-heap, replace the top of the max-heap and call heapify on the new root of the heap.

    This would take O((n-k)logk) time to complete. Finally we would be left with just the k elements in the max-heap. You can call heapify k times to return all these k elements. This is another O(klogk).

    Overall time complexity would be O(k + (n-k)logk + klogk).

提交回复
热议问题