0
点赞
收藏
分享

微信扫一扫

【LeeCode】855. 考场就座

悄然丝语 2022-12-30 阅读 116

【题目描述】

在考场里,一排有 ​​N​​​ 个座位,分别编号为 ​​0, 1, 2, ..., N-1​​ 。

当学生进入考场后,他必须坐在能够使他与离他最近的人之间的距离达到最大化的座位上。如果有多个这样的座位,他会坐在编号最小的座位上。(另外,如果考场里没有人,那么学生就坐在 0 号座位上。)

返回 ​​ExamRoom(int N)​​ 类,它有两个公开的函数:其中,函数 ​​ExamRoom.seat()​​ 会返回一个 ​​int​​ (整型数据),代表学生坐的位置;函数 ​​ExamRoom.leave(int p)​​ 代表坐在座位 ​​p​​ 上的学生现在离开了考场。每次调用 ​​ExamRoom.leave(p)​​ 时都保证有学生坐在座位 ​​p​​ 上。

​​https://leetcode.cn/problems/exam-room/description/?orderBy=most_votes​​​


【示例】

【LeeCode】855. 考场就座_整型

【代码】官方

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* 2022-12-30
*/

class ExamRoom {
int N;
TreeSet<Integer> students;

public ExamRoom(int N) {
this.N = N;
students = new TreeSet();
}

public int seat() {
// 默认第一个学生的位置为0
int student = 0;
if (students.size() > 0) {
// 按数字大小返回第一个/最小的数字
int dist = students.first();
// 记录之前的一个位置(第一个学生默认是null)
Integer prev = null;
for (Integer s: students) {
if (prev != null) {
// 计算距离 (自己的位置 - 前面的位置) / 2
int d = (s - prev) / 2;
if (d > dist) {
dist = d;
student = prev + d;
}
}
// 默认第一个数字为pre
prev = s;
}
// 按数字大小返回最后一个/最大的数字
int tmp = students.last();
if (N - 1 - students.last() > dist)
student = N - 1;
}
// 默认直接添加第一个学生(座位号0)
students.add(student);
return student;
}

public void leave(int p) {
students.remove(p);
}

public void print(){
System.out.println(students);
}
}

/**
* Your ExamRoom object will be instantiated and called as such:
* ExamRoom obj = new ExamRoom(n);
* int param_1 = obj.seat();
* obj.leave(p);
*/

public class Test {
public static void main(String[] args) {
String[] arr = {"ExamRoom","seat","seat","seat","seat","leave","seat"};
ExamRoom obj = new ExamRoom(10);
obj.seat();
obj.seat();
obj.seat();
obj.seat();
obj.leave(4);
obj.seat();

// 打印结果
obj.print();
}
}



举报

相关推荐

0 条评论