K Closest Points
ID: 612; medium; *
Solution 1 (Java)
Notes
This is the min heap solution. The thought process is the most straight-forward.
Time complexity:
O(nlogn + klogn) = O(nlogn)
Solution 2 (Java)
Notes
This is the max heap solution.
If p2 is larger than p1, return positive values. This gives us a max heap, vice versa.
Time complexity:
O(nlogk + klogk) = O(nlogk)
.So, this max heap version is better than the min heap version though the latter is more straight-forward to think about. The reason is clear because
k
is bounded byn
.Heap is priority queue in Java and we customize the ordering by overriding the
Comparator
. We iterate the wholepoints
array and add each point to the priority queue. However, the priority queue only stores the top k closest points, as supposed to the min heap, which essentially sorts the points by their distance to the origin.Thus, the offer and poll methods actually take
O(logk)
time in this solution because the size of the heap is k.
Solution 3 (Java)
Notes
This is the quick select solution.
Time complexity:
O(n + klogk)
, which means this is the best solution so far.For the
quickSelect
method, it is important to know that it is finding the kth closest point. After it is done, we havepoints[0, ..., k - 1]
being the top k closest points. However, it is only guaranteed thatpoints[k - 1]
is the kth closest point, while the remainingpoints[0, ..., k - 2]
is not necessarily sorted. Thus, we eventually useArrays.sort()
to sort these remaining points.Although this solution gives the best time complexity, it requires us to know
quickSelect
very well. Moreover, using proper data structures is also important, so the max heap version is already a valid and efficient solution.
Last updated