美文网首页Leetcode/Java学习笔记
973. K Closest Points to Origin

973. K Closest Points to Origin

作者: 萧瑟空间 | 来源:发表于2019-02-17 08:30 被阅读0次

    这是一段如何:

    1. 新建class数据结构
    2. 复写PriorityQueue的Comparator
    3. 如何新建int array并赋值
      的演示代码;
      Java 默认 PriorityQueue 会将最小的值pop,复写Comparator的时候在A>B时return -1就可以让PriorityQueue每次pop出最大的值,符合本题的需求
    import java.util.*;
    
    class priorityQ {
        public int[][] kClosest(int[][] points, int K) {
            int length = points.length;
            if(length <= K){return points;}
            PriorityQueue<Point> queue = new PriorityQueue<>(new PointComparator());
            for(int i = 0; i < length; i++){
                Point tmp = new Point(points[i]);
                queue.add(tmp);
                while(queue.size() > K){
                    queue.poll();
                }
            }
            int[][] ans = new int[K][2];
            for(int j = 0; j < K; j++){
                ans[j] = queue.poll().reformat();
            }
            return ans;
        }
    
    
        class Point{
            private int x;
            private int y;
            private int distance;
            private int[] point;
    
            Point(int[] point){
                this.x = point[0];
                this.y = point[1];
                this.distance = this.x * this.x + this.y * this.y;
                this.point = point;
            }
    
            int distance(){
                return this.distance;
            }
    
            int[] reformat(){
                return this.point;
            }
        }
    
        class PointComparator implements Comparator<Point>{
            public int compare(Point point1, Point point2){
                if(point1.distance > point2.distance){
                    return -1;
                }
                else if(point1.distance < point2.distance){
                    return 1;
                }
                else{
                    return 0;
                }
            }
        }
    
        public static void main(String[] args){
            int[][] points = {{-1,3},{2,2},{5,7},{6,6}};
            priorityQ qQ = new priorityQ();
            int[][] reply = qQ.kClosest(points, 2);
            for(int[] tmp : reply){
                System.out.println(Arrays.toString(tmp));
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:973. K Closest Points to Origin

        本文链接:https://www.haomeiwen.com/subject/rhgweqtx.html