租房系统
in Algorithm Pageviews
请设计一个租房信息查询系统,需要具备下面几个基本功能:
AddRoom(int id, int area, int price, int rooms, vector<int> &address)
:在系统中增加一套编号为 id,面积为 area,月租金为 price,房间数量为 rooms,地址坐标为 address(x:横坐标, y: 纵坐标)的房源;DeleteRoom(int id)
:删除系统中编号为 id 的房源;QueryRoom(int area, int price, int rooms, vector<int> &address, vector<vector<int>> &orderBy)
:查询系统中符合筛选条件的房源,并按照要求返回房源编号的序列。其中:筛选条件:面积大于 area,月租金小于等于 price,卧室数为 rooms 的房源;
排序要求:按照 orderBy 中的排序条件依次进行排序;若按照 orderBy 排序结果仍然相同(包括orderBy为空),则按照房源编号升序排列;
- orderBy的元素格式为 [parameter, order]。
- parameter 的取值范围[1, 3],1表示area, 2表示price,2表示房源坐标与address的曼哈顿距离;
- order取值仅为1 或 -1,1表示升序,-1表示降序
例如 orderBy = [[3, 1], [1, -1]] 表示先按照曼哈顿距离升序排列,若曼哈顿距离相同,再按照面积降序排列,若依然相同,则按照编号升序排列。
示例1
输入
["RentSystem", "AddRoom", "AddRoom", "QueryRoom", "DeleteRoom"]
[[], [3,24,200,2,[0,1]], [1,10,400,2,[1,0]], [1,400,2,[1,1],[[3,1],[2,-1]]],[3]]
输出
[null, true, true, [1, 3], true]
代码实现如下
#include <bits/stdc++.h>
using namespace std;
class RentSystem {
public:
bool AddRoom(int id, int area, int price, int rooms, const vector<int> &address)
{
if (m_hashMap.count(id)) {
m_hashMap[id] = {area, price, rooms, address[0], address[1]};
return false;
}
m_hashMap[id] = {area, price, rooms, address[0], address[1]};
return true;
}
bool DeleteRoom(int id)
{
if (m_hashMap.count(id)) {
m_hashMap.erase(id);
return true;
}
return false;
}
vector<int> QueryRoom(int area, int price, int rooms,
const vector<int> &address, const vector<vector<int>> &orderBy)
{
vector<int> ids;
for (const auto &[id, tp] : m_hashMap) {
auto [ar, pr, ro, x, y] = tp;
if (ar >= area && pr <= price && ro == rooms) {
ids.emplace_back(id);
}
}
sort(ids.begin(), ids.end(), [&](int a, int b) {
auto [ara, pra, roa, xa, ya] = m_hashMap[a];
auto [arb, prb, rob, xb, yb] = m_hashMap[b];
auto disa = abs(xa, address[0]) + abs(ya, address[1]);
auto disb = abs(xb, address[0]) + abs(yb, address[1]);
for (const auto &order : orderBy) {
if (order[0] == 1 && (ara != arb)) {
return (order[1] == 1) ? ara < arb : ara > arb;
}
if (order[0] == 2 && (pra != prb)) {
return (order[1] == 1) ? pra < prb : pra > prb;
}
if (order[0] == 3 && (disa != disb)) {
return (order[1] == 1) ? disa < disb : disa > disb;
}
}
return a < b;
});
return ids;
}
private:
map<int, tuple<int, int, int, int, int>> m_hashMap;
};