Microsoft - Find the K closest points to the origin in a 2D plane
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Microsoft - Find the K closest points to the origin in a 2D plane相关的知识,希望对你有一定的参考价值。
Find the K closest points to the origin in a 2D plane, given an array containing N points.
用 max heap 做
/* public class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } */ public List<Point> findKClosest(Point[] p, int k) { PriorityQueue<Point> pq = new PriorityQueue<>(10, new Comparator<Point>() { @Override public int compare(Point a, Point b) { return (b.x * b.x + b.y * b.y) - (a.x * a.x + a.y * a.y); } }); for (int i = 0; i < p.length; i++) { if (i < k) pq.offer(p[i]); else { Point temp = pq.peek(); if ((p[i].x * p[i].x + p[i].y * p[i].y) - (temp.x * temp.x + temp.y * temp.y) < 0) { pq.poll(); pq.offer(p[i]); } } } List<Point> x = new ArrayList<>(); while (!pq.isEmpty()) x.add(pq.poll()); return x; }
以上是关于Microsoft - Find the K closest points to the origin in a 2D plane的主要内容,如果未能解决你的问题,请参考以下文章
[HDU1599]find the mincost route
zoj3605 Find the Marble --- 概率dp
一道题目- Find the smallest range that includes at least one number from each of the k lists