题解 | 孩子们的游戏(圆圈中最后剩下的数)
孩子们的游戏(圆圈中最后剩下的数)
https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6
#include <climits> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @param m int整型 * @return int整型 */ int LastRemaining_Solution(int n, int m) { // write code here std::vector<bool> v(n, true); int i = 0; int ret = n;//用来记录数组大小,方便还剩最后一个人时结束循环 while (ret > 1) { int count = m - 1;//count用来模拟喊到的次数 while (count) { if (v[i % n]) { count--; } i++; } while (!v[i % n])//检查下一个是否为false { i++; } v[i % n] = false; ret--; } i = 0; //查找数组中唯一一个true for (; i < n; i++) { if (v[i])break; } return i; } };