Bootstrap

1847. 最近的房间

1847. 最近的房间


题目链接:1847. 最近的房间

代码如下:

class Solution 
{
public:
	vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries)
	{
		sort(rooms.begin(), rooms.end(), [&](vector<int>& a, vector<int>& b)
			{
				return a[1] > b[1];
			});

		vector<int> query_ids(queries.size());
		iota(query_ids.begin(), query_ids.end(), 0);
		//按照minSize从大到小排序
		ranges::sort(query_ids, {}, [&](int i) { return -queries[i][1]; });

		vector<int> res(queries.size(), -1);
		set<int> room_ids;
		int j = 0;
		for (int i : query_ids)
		{
			int prefered_id = queries[i][0], minSize = queries[i][1];
			while (j < rooms.size() && rooms[j][1] >= minSize)
			{
				room_ids.insert(rooms[j][0]);
				j++;
			}

			int diff = INT_MAX;
			auto it = room_ids.lower_bound(prefered_id);
			if (it != room_ids.begin())
			{
				auto p = prev(it);
				diff = prefered_id - *p;	//左边的差
				res[i] = *p;
			}
			if (it != room_ids.end() && *it - prefered_id < diff) //右边的差更小
			{
				res[i] = *it;
			}
		}
		return res;
	}
};
;