首页 > 其他 > 详细

973. K Closest Points to Origin

时间:2020-05-31 10:40:42      阅读:26      评论:0      收藏:0      [点我收藏+]

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.)

 

Note:

  1. 1 <= K <= points.length <= 10000
  2. -10000 < points[i][0] < 10000
  3. -10000 < points[i][1] < 10000
class Solution {
    public int[][] kClosest(int[][] points, int k) {
        Map<Double, List<int[]>> map = new HashMap();
        for(int[] arr: points){
            double kk = help(arr);
            if(!map.containsKey(kk)){
                map.put(kk, new ArrayList());
            }
            map.get(kk).add(arr);
        }
        List<Integer> ks = new ArrayList(map.keySet());
        Collections.sort(ks);
        int[][] res = new int[k][2];
        List<int[]> list = new ArrayList();
        for(int i = 0; i < ks.size(); i++){
            int t = map.get(ks.get(i)).size();
            for(int j = 0; j < t; j++) list.add(map.get(ks.get(i)).get(j));
        }
        for(int i = 0; i < k; i++) res[i] = list.get(i);
        return res;
    }
    public double help(int[] point){
        return Math.sqrt(point[0]*point[0] + point[1]*point[1]);
    }
}

哎 我咋老走弯路

class Solution {
    public int[][] kClosest(int[][] points, int K) {
        int N = points.length;
        int[] dists = new int[N];
        for (int i = 0; i < N; ++i)
            dists[i] = dist(points[i]);

        Arrays.sort(dists);
        int distK = dists[K-1];

        int[][] ans = new int[K][2];
        int t = 0;
        for (int i = 0; i < N; ++i)
            if (dist(points[i]) <= distK)
                ans[t++] = points[i];
        return ans;
    }

    public int dist(int[] point) {
        return point[0] * point[0] + point[1] * point[1];
    }
}

同样的排序方法

973. K Closest Points to Origin

原文:https://www.cnblogs.com/wentiliangkaihua/p/12996293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!