在考场里,一排有 N 个座位,分别编号为 0, 1, 2, ..., N-1 。 当学生进入考场后,他必须坐在能够使他与离他最近的人之间的距离达到最大化的座位上。如果有多个这样的座位,他会坐在编号最小的座位上。(另外,如果考场里没有人,那么学生就坐在 0 号座位上。) 返回 ExamRoom(int N) 类,它有两个公开的函数:其中,函数 ExamRoom.seat() 会返回一个 int (整型数据),代表学生坐的位置;函数 ExamRoom.leave(int p) 代表坐在座位 p 上的学生现在离开了考场。每次调用 ExamRoom.leave(p) 时都保证有学生坐在座位 p 上。 请使用Go实现
时间: 2023-02-09 10:25:43 浏览: 96
以下是用 Go 语言实现的 ExamRoom 类的代码示例:
```go
type ExamRoom struct {
// N 表示座位总数
N int
// seats 表示当前坐在考场里的学生的座位编号
seats []int
}
func Constructor(N int) ExamRoom {
return ExamRoom{N: N}
}
func (er *ExamRoom) Seat() int {
// 如果考场里没有人,则学生坐在 0 号座位上
if len(er.seats) == 0 {
er.seats = append(er.seats, 0)
return 0
}
// 在座位 0 和座位 N-1 之间查找最大间距
maxGap := er.seats[0]
seat := 0
for i := 1; i < len(er.seats); i++ {
gap := (er.seats[i] - er.seats[i-1]) / 2
if gap > maxGap {
maxGap = gap
seat = er.seats[i-1] + gap
}
}
// 如果座位 0 的间距比其他所有间距都大,则学生坐在座位 0 上
if er.N-1-er.seats[len(er.seats)-1] > maxGap {
seat = 0
}
// 将学生的座位编号加入 seats 切片
er.seats = append(er.seats, seat)
sort.Ints(er.seats)
return seat
}
func (er *ExamRoom) Leave(p int) {
// 从 seats 切片中删除座位 p
for i, seat := range er.seats {
if seat == p {
er.seats = append(er.seats[:i], er.seats[i+1:]...)
break
}
}
}
```
在这个实现中,ExamRoom 类包含两个公开函数:Seat 和 Leave。Seat 函数在考场里找到最大间距并返回能使学生与离他最近的人之间的距离达到最大化的座位的编号。Leave