LeetCode·每日一题·855.考场就座·有序集合+模拟

作者:小迅
链接:https://leetcode.cn/problems/exam-room/solutions/2037672/you-xu-ji-he-mo-ni-zhu-shi-chao-ji-xiang-flhc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 

题目

 

示例

 

思路

题意 -> 在给定的集合中插入一个元素,插入规则为 使得插入的点与最近的元素的距离最大,如果存在多个这样的点取序列最小的位置

我们可以直接按照题目给定的要求,创建一个集合,将所有元素按要求插入,并维护这个序列即可。

当然直接维护集合时间肯定会超时,所有需要使用一些小技巧来优化维护过程。

对于任意一个元素的插入位置,我们需要找到当前集合中,两个元素位置之间相乘的最大值,那么如何快速的找到这个位置,我们就需要使用有序集合来优化,我们对所有插入的元素,进行升序排列,对于位置相差最大的两个元素只需要枚举集合中的所有元素即可,因为集合中的元素时有序的。

对于任意一个元素的删除位置,我们可以使用双指针找到需要删除的位置,然后将后序的元素向前移位即可

代码注释超级详细

代码

typedef struct {
    int *ans;
    int size;
    int n; 
} ExamRoom;


ExamRoom* examRoomCreate(int n) {
    ExamRoom *obj = (ExamRoom *)malloc(sizeof(ExamRoom));
    obj->ans = (int *)malloc(sizeof(int) * 10001);
    obj->size = 0;
    obj->n = n;//初始化
    return obj;
}

int cmp(const void *a, const void *b) //排序函数
{
    return *(int *)a - *(int *)b;
}
int examRoomSeat(ExamRoom* obj) {
    if (obj == NULL) {
        return -1;
    }
    if (obj->size == 0) {obj->ans[obj->size++] = 0; return 0;} //没有人时,一定返回0
    int pre = obj->ans[0], ans = obj->ans[0], idx = 0; //初始话为选择最左的长度
    for (int x = 0; x < obj->size; ++x) {//枚举所有元素的位置,取最大位置
        if (ans < (obj->ans[x] - pre) / 2) {
            ans = (obj->ans[x] - pre) / 2;
            idx = (obj->ans[x] + pre) / 2;
        }
        pre = obj->ans[x];
    }
    //最右进行判断
    int d = obj->n - 1 - obj->ans[obj->size-1];
    if (ans < d) idx = obj->n - 1;
    obj->ans[obj->size++] = idx;
    qsort(obj->ans, obj->size, sizeof(int), cmp);//排序,维护有序集合
    return idx;
}

void examRoomLeave(ExamRoom* obj, int p) {
    if (obj == NULL) {
        return;
    }
    for (int i = 0, j = 0; i < obj->size; ++i) {/双指针删除
        if (obj->ans[i] == p) {
            continue;
        }
        obj->ans[j++] = obj->ans[i];
    }
    --obj->size;
    return;
}

void examRoomFree(ExamRoom* obj) {
    free(obj->ans);
    obj->ans = NULL;
    free(obj);
    obj = NULL;
}

/**
 * Your ExamRoom struct will be instantiated and called as such:
 * ExamRoom* obj = examRoomCreate(n);
 * int param_1 = examRoomSeat(obj);
 
 * examRoomLeave(obj, p);
 
 * examRoomFree(obj);
*/

作者:小迅
链接:https://leetcode.cn/problems/exam-room/solutions/2037672/you-xu-ji-he-mo-ni-zhu-shi-chao-ji-xiang-flhc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值