作者:小迅
链接:https://leetcode.cn/problems/exam-room/solutions/2037672/you-xu-ji-he-mo-ni-zhu-shi-chao-ji-xiang-flhc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目![](https://img-blog.csdnimg.cn/9ae25713867044f3acd391485176bab2.png)
示例![](https://img-blog.csdnimg.cn/2043d73013cb404ba811158ef1277b68.png)
思路
题意 -> 在给定的集合中插入一个元素,插入规则为 使得插入的点与最近的元素的距离最大,如果存在多个这样的点取序列最小的位置
我们可以直接按照题目给定的要求,创建一个集合,将所有元素按要求插入,并维护这个序列即可。
当然直接维护集合时间肯定会超时,所有需要使用一些小技巧来优化维护过程。
对于任意一个元素的插入位置,我们需要找到当前集合中,两个元素位置之间相乘的最大值,那么如何快速的找到这个位置,我们就需要使用有序集合来优化,我们对所有插入的元素,进行升序排列,对于位置相差最大的两个元素只需要枚举集合中的所有元素即可,因为集合中的元素时有序的。
对于任意一个元素的删除位置,我们可以使用双指针找到需要删除的位置,然后将后序的元素向前移位即可
代码注释超级详细
代码
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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。