Use priority queue to find the K closest points to the origin
In this problem, we will find the K closest points to the origin in the 2D plane from the given N points.
We can use the standard Euclidean distance formula to calculate the distance between the origin and each given point. After that, we can store the points with distance into an array, sort the array based on distance, and take the top K points.
However, we can also use a priority queue to store 2D points based on their distance from the origin. Afterwards, we can dequeue K times from the queue.
Problem Statement− We are given N points on the two-dimensional plane. We need to find the K points closest to the origin of the plane.
Note - Treat Euclidean distance as the distance between the origin and a given point on the plane.
Example
enter
points = {{2, -2}, {-5, 1}, {2, 1}, {0, 3}, {6, 0}, {5, 5}, {4, 9}}, K = 4
Output
{2,1} {2,-2} {0,3} {-5,1}
Explanation − Here is the Euclidean distance from each point to the origin.
(2, −2) −> sqrt(8)
(−5, 1) −> sqrt(26)
(2, 1) -> sqrt(5)
(0, 3) −> sqrt(9)
(6, 0) -> sqrt(36)
(5, 5) -> sqrt(50)
(4, 9) -> sqrt(97)
Therefore, the 4 closest points are {2,1} {2,−2} {0,3} {−5,1}.
enter
points = {{1, 2}, {2, 1}, {-2, 1}, {1, -2}} K = 2
Output
{1, 2}, {2, 1}
Explanation − The distance from all points to the origin is the same. Therefore, we can print any 2 points as output.
enter
points = {{1, 3}, {6, 7}, {1, 1}, {1, 0}} K = 4
Output
{1, 0}, {1, 1}, {1, 3}, {6, 7}
Explanation− K is equal to the given point. Therefore, we need to print all points.
method one
In this method, we will sort the array using sort() method. Additionally, we will use a comparator function to sort the points based on their distance from the origin. After that, we print the first K elements of the sorted array.
algorithm
Step 1 − Use the sort() method to sort the list and pass the distComparator() function as the third parameter.
Step 2− Define the distComparator() function to compare the distance of a given point. This function takes as parameters a pair of p and q.
Step 2.1 − Get the distance from point p to the origin and store it in dist_p.
Step 2.2 − Store the distance from point q to the origin in the dist_q variable.
Step 2.3 − If dist_p is less than dist_q, return true. Otherwise, returns false.
Step 3- Iterate through the array and print the first K points of the array.
Example
#include <bits/stdc++.h> using namespace std; bool distComparator(const pair<int, int> &p, const pair<int, int> &q) { int dist_p = p.first * p.first + p.second * p.second; int dist_q = q.first * q.first + q.second * q.second; return dist_p < dist_q; } vector<pair<int, int>> findKPoints(vector<pair<int, int>> points, int n, int k) { vector<pair<int, int>> res_points; sort(points.begin(), points.end(), distComparator); // Get the first K points for (int p = 0; p < k; p++) { res_points.push_back({points[p].first, points[p].second}); } return res_points; } int main() { int k = 4, n = 7; vector<pair<int, int>> points{{2, -2}, {-5, 1}, {2, 1}, {0, 3}, {6, 0}, {5, 5}, {4, 9}}; vector<pair<int, int>> res = findKPoints(points, n, k); cout << "The " << k << " closest points from origin are - "; for (int p = 0; p < k; p++) { cout << "{" << res[p].first << "," << res[p].second << "} "; } return 0; }
Output
The 4 closest points from origin are - {2,1} {2,-2} {0,3} {-5,1}
Time complexity - The time complexity of sorting an array is O(NlogN).
Space Complexity - O(N) for sorting the array.
Method Two
In this method, we will use priority queue to insert points. Additionally, we will use a comparator function and a priority queue to store points based on their shortest distance from the origin.
algorithm
Step 1 − Define the ‘res_points’ list to store the K nearest points.
Step 2- Define priority queue. Here, ‘pair
Step 3− Define the cmp() function to compare the Euclidean distance between two points and the origin.
Step 3.1 - Return a Boolean value based on the distance from point a to the origin being greater than the distance from point b to the origin.
Step 4 - Insert each element of the array into the priority queue.
Step 5− Pop the first K elements from the queue and store them in the res_points list.
Step 6− Return the res_points list of points.
Example
#include <bits/stdc++.h> using namespace std; vector<pair<int, int>> findKPoints(vector<pair<int, int>> points, int n, int k) { vector<pair<int, int>> res_points; // Custom comparator to compare points based on their distance from the origin auto cmp = [](const pair<int, int>& a, const pair<int, int>& b) { return (a.first * a.first + a.second * a.second) > (b.first * b.first + b.second * b.second); }; // Use the custom comparator in the priority_queue priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> p_que(cmp); for (int p = 0; p < n; p++) { // Inserting points in a queue p_que.push(points[p]); } // Get first K points while (k--) { auto temp = p_que.top(); res_points.push_back(temp); p_que.pop(); } return res_points; } int main() { int k = 4, n = 7; vector<pair<int, int>> points{{2, -2}, {-5, 1}, {2, 1}, {0, 3}, {6, 0}, {5, 5}, {4, 9}}; vector<pair<int, int>> res = findKPoints(points, n, k); cout << "The " << k << " closest points from origin are - "; for (int p = 0; p < k; p++) { cout << "{" << res[p].first << "," << res[p].second << "} "; } return 0; }
Output
The 4 closest points from origin are - {2,1} {2,-2} {0,3} {-5,1}
Time complexity - O(N*logN) Insert N elements into the priority queue. Here, N is the total number of points.
Space Complexity - O(N) to store points in priority queue.
Priority queue uses heap data structure. Therefore, inserting and deleting elements only takes O(logN) time. Both methods require the same memory and time. However, the second method is more efficient because it uses the heap data structure.
The above is the detailed content of Use priority queue to find the K closest points to the origin. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of Redis implementation of priority queue Priority queue is a common data structure that can sort elements according to certain rules and maintain this order during queue operations, so that elements taken out of the queue always follow the preset priority conduct. As an in-memory database, Redis also has advantages in implementing priority queues because of its fast and efficient data access capabilities. This article will introduce in detail the method and application of Redis to implement priority queue. 1. Basic principles of Redis implementation Basic principles of Redis implementation of priority queue

Heap and priority queue are commonly used data structures in C++, and they both have important application value. This article will introduce and analyze the heap and priority queue respectively to help readers better understand and use them. 1. Heap is a special tree data structure that can be used to implement priority queues. In the heap, each node satisfies the following properties: its value is not less than (or not greater than) the value of its parent node. Its left and right subtrees are also a heap. We call a heap that is no smaller than its parent node a "min-heap" and a heap that is no larger than its parent node a "max-heap"

What are the usage scenarios of heap and priority queue in Python? The heap is a special binary tree structure that is often used to efficiently maintain a dynamic collection. The heapq module in Python provides a heap implementation and can easily perform heap operations. A priority queue is also a special data structure. Unlike an ordinary queue, each element of it has a priority associated with it. The highest priority element is taken out first. The heapq module in Python can also implement the priority queue function. Below we introduce some

With the continuous development of society, people's requirements for computer technology are becoming higher and higher. In computers, queues are a very important data structure that can help us solve many problems efficiently. However, in actual application processes, the efficiency of the queue is often limited by some factors, such as network delay, database query speed, etc. So, today we will introduce a way to solve this problem: using Memcache caching technology in PHP to improve the efficiency of the priority queue. 1. What is a priority queue?

In this problem, we will find the K points in the 2D plane that are closest to the origin from the given N points. We can use the standard Euclidean distance formula to calculate the distance from the origin to each given point. After that, we can store the points with distance into an array, sort the array based on distance, and take the top K points. However, we can also use a priority queue to store 2D points based on their distance from the origin. Afterwards, we can dequeue K times from the queue. Problem Statement − We are given N points on a two-dimensional plane. We need to find the K points closest to the origin of the plane. Note - Think of Euclidean distance as the distance between the origin and a given point on the plane. Example input points={{2,-2},{-5,1},{2,1},{

Priority queues allow elements to be stored and accessed by priority, setting priorities based on comparable criteria such as value, timestamp, or custom logic. Implementation methods in PHP include the SplPriorityQueue class and Min/Max heap. The practical case demonstrates how to use the SplPriorityQueue class to create a priority queue and obtain elements by priority.

How are heap and priority queue implemented in Python? Heaps and priority queues are commonly used data structures in computer science. In Python, we can use the heapq module to implement heaps and priority queues. A heap is a special kind of complete binary tree. In the heap, the value of each parent node is smaller (or larger) than the value of its child node. Such a heap is called a small root heap (or large root heap). In Python, a heap can be represented by a list. Python's heapq module provides some methods to manipulate the heap. first

The circumference of a circle can be defined as the outer boundary of the circle. It is the circumference of the circle. Every point around a circle follows certain properties as follows - Point (x,y) lies inside the circle such that $\mathrm{x^2+y^2R^2}$ where R=radius of the circle. Problem Statement Given a string S representing a sequence of moves (L, R, U, D) and an integer R representing the radius of a circle. Check whether any point on the circumference of a circle of radius R with the origin can be reached by selecting any subsequence of moves starting from S. The operation of each move is as follows, L = Decrease x coordinate R = Increment x coordinate U = Increment y coordinate D = Decrease y coordinate Example 1 Input S = "RURDLR" R = 2 Output Yes Description Select subsequence "RR "-initial,(
