• 973. K Closest Points to Origin


    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];
        }
    }

    同样的排序方法

  • 相关阅读:
    Go语言中DateTime知识点
    Go语言中的string知识点
    Go语言中的Iota
    Go语言的通道(2)-缓冲通道
    Go语言的通道(1)-无缓冲通道
    Go语言协程
    设计一个好的通用组件
    Windows服务器【由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作】问题调查
    Go语言的并发
    SCSS 中的 &::before 和 &::after
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12996293.html
Copyright © 2020-2023  润新知