[LeetCode] K-th Nearest Obstacle Queries

3275. K-th Nearest Obstacle Queries

There is an infinite 2D plane.

You are given a positive integer k. You are also given a 2D array queries, which contains the following queries:

  • queries[i] = [x, y]: Build an obstacle at coordinate (x, y) in the plane. It is guaranteed that there is no obstacle at this coordinate when this query is made.

After each query, you need to find the distance of the kth nearest obstacle from the origin.

Return an integer array results where results[i] denotes the kth nearest obstacle after query i, or results[i] == -1 if there are less than k obstacles.

Note that initially there are no obstacles anywhere.

The distance of an obstacle at coordinate (x, y) from the origin is given by |x| + |y|.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> resultsArray(vector<vector<int>>& queries, int k) {
priority_queue<int> q;
vector<int> res;
for(auto& qry : queries) {
q.push(abs(qry[0]) + abs(qry[1]));
while(q.size() > k) q.pop();
res.push_back(q.size() < k ? -1 : q.top());
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/01/PS/LeetCode/k-th-nearest-obstacle-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.