演示:
五个人:围成圈
a,b,c,d,e
每传到第五次,当前的人淘汰,直到最后一个人了。
a,b,c,d,e => e出去,
a,b,c,d,a=> a出去
b,c,d,b,c => c出去,
d,b,d,b,d=> d出去 => 只剩b了。
用队列思考:
const q = new Queue(["a", "b", "c", "d", "e"]);
let timer = 0;
//第一次淘汰:
while (timer < 5) {
const dequeue = q.dequeue();
timer !== 4 && q.enqueue(dequeue);
timer === 4 && console.log(dequeue,q);
timer++
}
timer = 0;
//第2次淘汰:
while (timer < 5) {
const dequeue = q.dequeue();
timer !== 4 && q.enqueue(dequeue);
timer === 4 && console.log(dequeue,q);
timer++
}
timer = 0;
//第3次淘汰:
while (timer < 5) {
const dequeue = q.dequeue();
timer !== 4 && q.enqueue(dequeue);
timer === 4 && console.log(dequeue,q);
timer++
}
timer = 0;
//第4次淘汰:
while (timer < 5) {
const dequeue = q.dequeue();
timer !== 4 && q.enqueue(dequeue);
timer === 4 && console.log(dequeue,q);
timer++
}
// 1 Queue { lists: [ 2, 3, 6, 7, 8, 9 ] }
// e Queue { lists: [ 'a', 'b', 'c', 'd' ] }
// a Queue { lists: [ 'b', 'c', 'd' ] }
// c Queue { lists: [ 'd', 'b' ] }
// d Queue { lists: [ 'b' ] }
归纳:
function drummingFlowers(arr, loopNum) {
const q = new Queue(arr);
let timer = 1;
while (q.size() > 1) {
const dequeue = q.dequeue();
timer % loopNum !== 0 && q.enqueue(dequeue);
timer++
}
return q.front();
}