difficulty: Medium tags:

  • Heap
  • Amazon
  • LinkedIn title: K Closest Points

K Closest Points

Problem

Metadata

Description

Given some points and a point origin in two dimensional space, find k points out of the some points which are nearest to origin. Return these points sorted by distance, if they are same with distance, sorted by x-axis, otherwise sorted by y-axis.

Example

Given points = [[4,6],[4,7],[4,4],[2,5],[1,1]], origin = [0, 0], k = 3 return [[1,1],[2,5],[4,4]]

题解

和普通的字符串及数目比较,此题为距离的比较。

Java

  1. /**
  2. * Definition for a point.
  3. * class Point {
  4. * int x;
  5. * int y;
  6. * Point() { x = 0; y = 0; }
  7. * Point(int a, int b) { x = a; y = b; }
  8. * }
  9. */
  10. public class Solution {
  11. /**
  12. * @param points: a list of points
  13. * @param origin: a point
  14. * @param k: An integer
  15. * @return: the k closest points
  16. */
  17. public Point[] kClosest(Point[] points, Point origin, int k) {
  18. // write your code here
  19. Queue<Point> heap = new PriorityQueue<Point>(new DistanceComparator(origin));
  20. for (Point point : points) {
  21. if (heap.size() < k) {
  22. heap.offer(point);
  23. } else {
  24. Point peek = heap.peek();
  25. if (distance(peek, origin) <= distance(point, origin)) {
  26. continue;
  27. } else {
  28. heap.poll();
  29. heap.offer(point);
  30. }
  31. }
  32. }
  33. int minK = Math.min(k, heap.size());
  34. Point[] kClosestPoints = new Point[minK];
  35. for (int i = 1; i <= minK; i++) {
  36. kClosestPoints[minK - i] = heap.poll();
  37. }
  38. return kClosestPoints;
  39. }
  40. public int distance(Point p, Point origin) {
  41. return (p.x - origin.x) * (p.x - origin.x) +
  42. (p.y - origin.y) * (p.y - origin.y);
  43. }
  44. class DistanceComparator implements Comparator<Point> {
  45. private Point origin = null;
  46. public DistanceComparator(Point origin) {
  47. this.origin = origin;
  48. }
  49. public int compare(Point p1, Point p2) {
  50. int d1 = distance(p1, origin);
  51. int d2 = distance(p2, origin);
  52. if (d1 != d2) {
  53. return d2 - d1;
  54. } else {
  55. if (p1.x != p2.x) {
  56. return p2.x - p1.x;
  57. } else {
  58. return p2.y - p1.y;
  59. }
  60. }
  61. }
  62. }
  63. }

源码分析

注意 Comparator 的用法和大小根堆的选择即可。

复杂度分析

堆的删除插入操作,最大为 K, 故时间复杂度为 O(n \log k), 空间复杂度为 O(K).