题目链接:https://leetcode.cn/problems/the-number-of-the-smallest-unoccupied-chair/
题目大意:给出一群人到达一个排队的时间和离开派对的时间[arr, lev]
。有无数个座位,下标从0开始。当一个人在tm
时刻离开时,如果一个人在tm
及其以后的时刻到达,那么他可以坐离开的人的座位。每个人会优先挑选下标最小的座位。给出一个targetFriend,求这个人坐到的座位号。【题目保证每个人到达的时间是不同的】
思路:首先,对于每个人的处理肯定是按照到达时间的先后顺序,我们要考虑的那个人的时间假设为arr_i
,那么实际上arr_i
之后到达的人就根本没必要去考虑了。因此,先把arr_i
以及之前到达的人找出来,再按照时间顺序排序。
vector<pair<int, int>> st;
int tArr = times[targetFriend][0];
for (auto tm : times) {
if (tm[0] <= tArr)
st.push_back(make_pair(tm[0], tm[1]));
}
随后,对这群需要处理的人遍历即可。(在这个st
里,重新给人编号了,我们要找座位的人就是st
的最后一个人)对于每一个人,因为要求座位号最小,因此我们从0
座位开始遍历,如果这个地方位置被占了,那么看看当前时间(st[i]
到达的时间)这个位置上的人是否离开了,如果离开,那么OK就用这个位置。如果这个地方位置没被占,那也OK就用这个位置。
其中occ[]
记录该位置上坐的上一个人,如果是-1
表示还没有被坐过。
for (int i = 0; i < st.size(); i++) {
int pos = 0;
int now = st[i].first;
while (occ[pos] != -1) {
if (now >= st[occ[pos]].second) {
break;
}
pos++;
}
occ[pos] = i;
if (i == st.size()-1)
ret = pos;
}
记录最后一个人(我们的目标)坐的座位,返回即可。
完整代码:
bool cmp(pair<int, int> x, pair<int, int> y) {
return x.first < y.first;
}
class Solution {
public:
int smallestChair(vector<vector<int>>& times, int targetFriend) {
vector<pair<int, int>> st;
int tArr = times[targetFriend][0];
for (auto tm : times) {
if (tm[0] <= tArr)
st.push_back(make_pair(tm[0], tm[1]));
}
int occ[100001];
memset(occ, -1, sizeof(occ));
sort(st.begin(), st.end(), cmp);
int ret = -1;
for (int i = 0; i < st.size(); i++) {
int pos = 0;
int now = st[i].first;
while (occ[pos] != -1) {
if (now >= st[occ[pos]].second) {
break;
}
pos++;
}
occ[pos] = i;
if (i == st.size()-1)
ret = pos;
}
return ret;
}
};