Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
K closest points
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { System.out.println("Hello, World!"); } public static int[][] kClosest(int[][] points, int K) { //create Max Heap //creating priority queue that compares two points p1 & p2. Returns 1 or -1 or 0 based on which point is farther from origin. // e.g. - for points (x1,y1) and (x2,y2), the following line gives 1 or -1 or 0 : // (x1*x1 + y1*y1) - (x2*x2 + y2*y2) PriorityQueue<int[]> pq = new PriorityQueue<>((p1,p2)->(p2[0]*p2[0]+p2[1]*p2[1]) - (p1[0]*p1[0]+p1[1]*p1[1]) ); for(int[] point:points){ pq.add(point); if(pq.size()>K) pq.poll(); } //return heap elements int[][] out = new int[K][2]; for(int i = 0;i<K;i++){ out[i] = pq.poll(); } return out; } }
run
|
edit
|
history
|
help
0
2darray
Escaping Literals (Table of records)
Problem_binary
Huffman Encoding Tree
Leetcode 17. Letter Combinations of a Phone Number
karyawan
log
4a
Kochergina_4
Continue