个人练习-Leetcode-1942. The Number of the Smallest Unoccupied Chair

题目链接: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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值