题目:2940. 找到 Alice 和 Bob 可以相遇的建筑
思路:知道A、B的位置下标x、y后(确保x<y),如果x==y或heights[x]<heights[y],那最左边的建筑就是y。否则我们就将其存到g[y]中,进行后续的离线法。细节看注释
class Solution {
public:
typedef pair<int,int> PII;
vector<int> leftmostBuildingQueries(vector<int>& heights, vector<vector<int>>& queries) {
int n=heights.size(),m=queries.size();
//需要返回的答案
vector<int> v(m,-1);
//用于保存询问(离线法)
vector<PII> g[n];
for(int i=0;i<m;i++){
//得到A、B的位置下标x、y(确保x<y)
int x=queries[i][0],y=queries[i][1];
if(x>y){
swap(x,y);
}
//最左边的建筑就是y
if(x==y||heights[x]<heights[y]){
v[i]=y;
}else{
//否则我们就将其存到g[y]中,进行后续的离线法
g[y].push_back({heights[x],i});
}
}
//优先队列,小顶堆
priority_queue<PII,vector<PII>,greater<>> qu;
//开始遍历heights
for(int i=0;i<n;i++){
//如果当前队列不空,且最前面的值小于当前的heights[i]
while(!qu.empty()&&qu.top().first<heights[i]){
//那就说明第qu.top().second次询问最左边的建筑是i
v[qu.top().second]=i;
qu.pop();
}
//将该位置的询问都插入到小顶堆当中
for(auto x:g[i]){
qu.push(x);
}
}
return v;
}
};