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 kthnearest 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|.
Input: queries =[[1,2],[3,4],[2,3],[-3,0]], k =2Output: [-1,7,5,3]Explanation:
* Initially, there are 0 obstacles.* After `queries[0]`, there are less than 2 obstacles.* After `queries[1]`, there are obstacles at distances 3 and 7.* After `queries[2]`, there are obstacles at distances 3,5, and 7.* After `queries[3]`, there are obstacles at distances 3,3,5, and 7.
Input: queries =[[5,5],[4,4],[3,3]], k =1Output: [10,8,6]Explanation:
* After `queries[0]`, there is an obstacle at distance 10.* After `queries[1]`, there are obstacles at distances 8 and 10.* After `queries[2]`, there are obstacles at distances 6,8, and 10.
To efficiently track the k-th nearest obstacle after each query, use a max-heap (priority queue) of size at most k. The heap always contains the k smallest distances seen so far, so the top is the k-th nearest. If fewer than k obstacles, return -1.
classSolution {
public List<Integer>kthNearestObstacle(int[][] queries, int k) {
PriorityQueue<Integer> pq =new PriorityQueue<>(Collections.reverseOrder());
List<Integer> ans =new ArrayList<>();
for (int[] q : queries) {
int d = Math.abs(q[0]) + Math.abs(q[1]);
pq.offer(d);
if (pq.size() > k) pq.poll();
ans.add(pq.size() == k ? pq.peek() : -1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funkthNearestObstacle(queries: Array<IntArray>, k: Int): List<Int> {
val pq = java.util.PriorityQueue<Int>(compareByDescending { it })
val ans = mutableListOf<Int>()
for (q in queries) {
val d = kotlin.math.abs(q[0]) + kotlin.math.abs(q[1])
pq.add(d)
if (pq.size > k) pq.poll()
ans.add(if (pq.size == k) pq.peek() else -1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
import heapq
classSolution:
defkthNearestObstacle(self, queries: list[list[int]], k: int) -> list[int]:
pq: list[int] = []
ans: list[int] = []
for x, y in queries:
d = abs(x) + abs(y)
heapq.heappush(pq, -d)
if len(pq) > k:
heapq.heappop(pq)
ans.append(-pq[0] if len(pq) == k else-1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::BinaryHeap;
impl Solution {
pubfnkth_nearest_obstacle(queries: Vec<Vec<i32>>, k: i32) -> Vec<i32> {
letmut pq = BinaryHeap::new();
letmut ans =vec![];
for q in queries {
let d = q[0].abs() + q[1].abs();
pq.push(d);
if pq.len() > k asusize { pq.pop(); }
ans.push(if pq.len() == k asusize { *pq.peek().unwrap() } else { -1 });
}
ans
}
}