From 52b811141f0c27e88abea558aee68cecdabc837e Mon Sep 17 00:00:00 2001 From: joney000 Date: Sat, 1 Jan 2022 21:02:36 +0530 Subject: [PATCH] add priority queue --- Algorithms/PriorityQueue.java | 36 +++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 37 insertions(+) create mode 100644 Algorithms/PriorityQueue.java diff --git a/Algorithms/PriorityQueue.java b/Algorithms/PriorityQueue.java new file mode 100644 index 0000000..4894f0d --- /dev/null +++ b/Algorithms/PriorityQueue.java @@ -0,0 +1,36 @@ +class Solution { + + class Point{ + int x, y; + int distance; + public Point(int x, int y){ + this.x = x; + this.y = y; + this.distance = x * x + y * y; + } + + } + + // returns the K Closest points from origin (0, 0) + // Time: O(n log k), space: O(k) + public int[][] kClosest(int[][] points, int k) { + if(points.length == 0 || k > points.length){ + return null; + } + int numPoints = points.length; + PriorityQueue pQueue = new PriorityQueue(k + 1, (a,b) -> (b.distance - a.distance)); // max elem on top + for(int[] point: points){ + pQueue.add(new Point(point[0], point[1])); + if(pQueue.size() > k){ + pQueue.poll(); + } + } + int[][] sortedElements = new int[k][2]; + for(int pos = k - 1; pos >= 0; pos--){ + Point point = (Point)pQueue.poll(); + sortedElements[pos][0] = point.x; + sortedElements[pos][1] = point.y; + } + return sortedElements; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 24e5997..8b31165 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ In This Repository, I have written some of the important Algorithms and Data Str | [Kth Order Statics](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/kthOrderStatics.java)|O(N), O(N) | K’th Smallest/Largest Element in Unsorted Array | [Trie / Prefix Tree](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/Trie.java)| O(N * L), O(N * L)| if there are N strings of L size, per query time(Prefix information) = O(L) | [LIS - Longest Increasing Subsequence](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/LIS_nLOGn.java)| O(N * log(N)), O(N) +| [Priority Queue](https://github.com/joney000/Java-Competitive-Programming/blob/master/Algorithms/PriorityQueue.java)| O(log(N)), O(N) | N = no of objects in the queue. peek: O(1), poll/add: O(log n) ## Contributions