对每个询问,先找出符合实际房间体积,大于询问房间体积房间的房间号,之后再从这些符合条件的候选答案中挑选一个最接近询问房间ID号的。
为了找出符合条件的房间,可以对实际房间、询问房间,按照房间体积降序排序,然后只将大于等于询问房间体积的房间ID,加入到待筛选的房间列表中。因为对于小于询问房间体积的房间,是不会作为答案的。
同时保证待筛选的房间列表保存在一个有序的列表之中,这样就可以通过二分查找的方式,快速的找到最接近询问房间ID的房间ID,实现如下:
struct record
{
int originId;
int roomSize;
int roomId;
record(int _originId, int _roomSize, int _roomId)
{
this->originId = _originId;
this->roomSize = _roomSize;
this->roomId = _roomId;
}
};
bool compare__(const record& a, const record& b)
{
return a.roomSize > b.roomSize;
}
class Solution {
public:
vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {
vector<record> roomRecords;
vector<record> queryRecords;
for(int i = 0; i < rooms.size(); i++)
{
roomRecords.emplace_back(record(i, rooms[i][1], rooms[i][0]));
}
for(int i = 0; i < queries.size(); i++)
{
queryRecords.emplace_back(record(i, queries[i][1], queries[i][0]));
}
sort(roomRecords.begin(), roomRecords.end(), compare__);
sort(queryRecords.begin(), queryRecords.end(), compare__);
vector<int> res(queries.size(), -1);
set<int> curRoomIdSet;
int j = 0;
for(int i = 0; i < queryRecords.size(); i++)
{
int curRoomID = queryRecords[i].roomId;
int curRoomSize = queryRecords[i].roomSize;
int curQueryID = queryRecords[i].originId;
while(j < roomRecords.size() && roomRecords[j].roomSize >= curRoomSize)
{
curRoomIdSet.insert(roomRecords[j].roomId);
j++;
}
int dist = INT_MAX;
auto it = curRoomIdSet.lower_bound(curRoomID);
if(it != curRoomIdSet.begin())
{
auto p = prev(it);
dist = curRoomID - *p;
res[curQueryID] = *p;
}
if(it != curRoomIdSet.end() && *it - curRoomID < dist)
res[curQueryID] = *it;
}
return res;
}
};
标签:int,roomRecords,房间,1847,力扣,vector,roomSize,queryRecords,刷题
From: https://www.cnblogs.com/yuhixyui/p/18635954