-
[알고리즘] K Closest Points to Origin알고리즘/배열 2021. 4. 19. 14:42
Problem
Key Point
Priority Queue (min heap)
Queue<int[]> priorityQueue = new PriorityQueue<>((a,b) -> (a[0]*a[0]+a[1]*a[1])-(b[0]*b[0]+b[1]*b[1]));
Code
public class KClosest { public int[][] solution(int[][] points, int k) { int[][] result = new int[k][2]; Queue<int []> pq = new PriorityQueue<>((a,b) -> (a[0]*a[0]+a[1]*a[1])-(b[0]*b[0]+b[1]*b[1])); for (int[] p : points) { pq.offer(p); } System.out.println(pq); int index = 0; while (index < k) { result[index] = pq.poll(); index++; } return result; } public static void main(String[] args) { KClosest kClosest = new KClosest(); int k = 1; int[][] points = {{1, 3}, {-2, 2}}; kClosest.solution(points, k); } }
'알고리즘 > 배열' 카테고리의 다른 글
[알고리즘] Merge Intervals (O) (0) 2021.04.20 [알고리즘] Meeting Rooms II (0) 2021.04.20 [알고리즘] Jewels And Stones (0) 2021.04.20 [알고리즘] License Key Formatting (0) 2021.04.19 [알고리즘] Plus One (0) 2021.04.19