JZ46 孩子们的游戏

本文最后更新于:2022年4月9日 中午

image-20211010150446620

Solution

  • 模拟法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int LastRemaining_Solution(int n, int m) {
if (n <= 0 || m < 0) return -1;
// 利用数组模拟环删除过程
vector<int> nums(n, 0);
int index = -1, step = 0, count = n;
while (count >0) {
index++; // 指向上一个被删除对象的下一个元素
if (index >= n) index = 0; // 模拟环
if (nums[index] == -1) continue; // 跳过被删除的元素
step++; // 记录已经走过的
if (step == m) { // 找到待删除对象
nums[index] = -1;
step = 0;
count--;
}
}
return index; // 返回最后一个被设为 -1 的元素
}
};
  • 约瑟夫环,利用公式
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int LastRemaining_Solution(int n, int m) {
// 约瑟夫环
if (n <= 0 || m < 0) return -1;
int res = 0;
for (int i = 2; i <= n; ++i) {
res = (res + m) % i;
}
return res;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!