zoukankan      html  css  js  c++  java
  • [leetcode]973. K Closest Points to Origin 离原点距离最近的K个点

    We have a list of points on the plane.  Find the K closest points to the origin (0, 0).

    (Here, the distance between two points on a plane is the Euclidean distance.)

    You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)

    Example 1:

    Input: points = [[1,3],[-2,2]], K = 1
    Output: [[-2,2]]
    Explanation: 
    The distance between (1, 3) and the origin is sqrt(10).
    The distance between (-2, 2) and the origin is sqrt(8).
    Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
    We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

    Example 2:

    Input: points = [[3,3],[5,-1],[-2,4]], K = 2
    Output: [[3,3],[-2,4]]
    (The answer [[-2,4],[3,3]] would also be accepted.)

    题意
    求离原点距离最近的K个点


    思路

    维护一个minHeap


    代码

     1 class Solution {
     2     public int[][] kClosest(int[][] points, int K) {
     3            int[][] res = new int[K][2];
     4 
     5         PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> (a[0] * a[0] + a[1] * a[1]) - (b[0] * b[0] + b[1] * b[1]));   
     6         for (int[] point : points) {
     7             minHeap.add(point);
     8         }
     9         
    10         for (int i = 0; i < K; i++) {
    11             res[i] = minHeap.poll();
    12         }
    13         return res;
    14 
    15     }
    16 }
  • 相关阅读:
    2021年2月13
    2021年2月12
    2021年2月11
    2021年2月10
    2021年2月9
    下载优化
    20180301越努力越轻松
    2018-03-01继续完善2
    2018-03-01继续完善
    2018-02-16 GetSameTypeQuestion
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/11124118.html
Copyright © 2011-2022 走看看