题目描述:
一个餐厅,有n个凳子排列成一排,人们进进出出。每个人都想坐在离别人尽量远的位置坐着吃饭,现在给你这些人进进出出的序号,请你输出这些人会坐在哪儿呢?如果有多个位置合法,人们喜欢坐在序号最小的凳子上面。
输入描述
第一行两个整数n,m,表示餐厅椅子数量和操作数。接下来m行,每行两个整数F和x。
F是1表示编号为x的人进入餐厅吃饭。F是2表示编号为x的人出餐厅。保证操作合法。满足n,m<=200000,x<=1000000
输出描述:对于所有操作1,输出一个整数,表示椅子的编号。
样例输入
7 11 1 15 1 123123 1 3 1 5 2 123123 2 15 1 21 2 3 1 6 1 7 1 8
样例输出
1 7 4 2 7 4 1 3
- 创建长度为n的,值为-1的数组,
- 循环判断客人进来坐哪
- 进来
- 求出连续空位,
- 若全是空位,坐在第一位,即下标为0的位置
- 否则找出最长的连续空位
- 如果连续空位在尾部,则坐在最后一个位置
- 如果连续空位<=2,则选一个全部座位中号最小的空位即可
- 否则 计算连续空位之前的位数+连续空位的中间位置 为落座位置
- 将该客人的编号放在座位上(seat数组里)
- 求出连续空位,
- 出去
- 将该位置置为空位(seat对应位子置-1)
- 进来
var printOut = function(n,arr){
//创建长度为n的,值为-1的数组
let seat = new Array(n).fill(-1)
//循环判断进来坐哪,出去置为-1空位
arr.forEach((itemson,itemindex)=>{
let [inout,noid] = itemson;
let copyseat = [...seat]
if(inout===1){//进来
//求出连续空位
let sameseat = []
while(copyseat.length){
let firstseat = copyseat[0]
let seatindex = copyseat.findIndex((m,n)=>{
if(m!==firstseat){
return n
}
})
seatindex>0
?sameseat.push(copyseat.splice(0,seatindex))
:sameseat.push(copyseat.splice(0,seat.length))
}
//求所坐位置下标
let inseat = 0
if(sameseat.length===1){
//若全是空位,坐在第一位,即下标为0的位置
}else{
//找出最长的连续空位
let maxlen = 0
let maxindex = 0
sameseat.forEach((item,index)=>{
(item[0]===-1 && item.length>maxlen) ? ((maxlen=item.length) && (maxindex=index)) :''
})
if(maxindex===sameseat.length-1){
//如果连续空位在尾部,则坐在最后一个位置
inseat = n-1
}else if(maxlen<=2){
//如果连续空位<=2,则选一个号最小的空位即可
inseat = seat.findIndex((item,index)=>{
return item===-1
})
}else{
//否则 计算连续空位之前的位数+连续空位的中间位置 为落座位置
let sumlen = 0
sameseat.forEach((item,index)=>{
if(index<maxindex){
sumlen+=item.length
}
})
inseat = sumlen+Math.ceil(maxlen/2)-1
}
}
seat[inseat] = noid
console.log(seat)
console.log(inseat+1)
}else{//出去
let outseat = seat.findIndex(item=>{
return item===noid
})
seat[outseat] = -1
console.log(seat)
}
})
}
printOut(7,[[1,15],[1,123123],[1,3],[1,5],[2,123123],[2,15],[1,21],[2,3],[1,6],[1,7],[1,8]])
结果:
//printOut(7,[[1,15],[1,123123],[1,3],[1,5],[2,123123],[2,15],[1,21],[2,3],[1,6],[1,7],[1,8]])
(7) [15, -1, -1, -1, -1, -1, -1]
1
(7) [15, -1, -1, -1, -1, -1, 123123]
7
(7) [15, -1, -1, 3, -1, -1, 123123]
4
(7) [15, 5, -1, 3, -1, -1, 123123]
2
(7) [15, 5, -1, 3, -1, -1, -1]
(7) [-1, 5, -1, 3, -1, -1, -1]
(7) [-1, 5, -1, 3, -1, -1, 21]
7
(7) [-1, 5, -1, -1, -1, -1, 21]
(7) [-1, 5, -1, 6, -1, -1, 21]
4
(7) [7, 5, -1, 6, -1, -1, 21]
1
(7) [7, 5, 8, 6, -1, -1, 21]
3