题解 | #孩子们的游戏(圆圈中最后剩下的数)#
孩子们的游戏(圆圈中最后剩下的数)
https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @param m int整型 * @return int整型 */ export function LastRemaining_Solution(n: number, m: number): number { // 将他们依次放在一个队列的数据结构中,当叫到的不是m-1的小朋友放到队列的后面,叫到的就离开,进行循环,直到剩下最后一个小朋友就是赢家 const stack = [] for(let i = 0;i < n;i++){ stack.push(i) } let count = 0 while(1){ if(stack.length === 1){ return stack[0] } if(count != m - 1){ const res = stack.shift() stack.push(res) count++ }else{ stack.splice(0,1) count = 0 } } }