题解 | 约瑟夫环
约瑟夫环
https://www.nowcoder.com/practice/e417cfe32c74416ca38247f619ddb322
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt(); // 起始位置
int m = in.nextInt(); // 报数到m的人出列
// 创建人员列表
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
list.add(i);
}
int currentIndex = k - 1; // 转换为0-based索引
while (list.size() > 1) {
// 计算要删除的位置
currentIndex = (currentIndex + m - 1) % list.size();
// 移除该位置的人
list.remove(currentIndex);
// 如果删除后列表为空,退出循环
if (list.isEmpty()) {
break;
}
// 调整索引,确保不越界
if (currentIndex >= list.size()) {
currentIndex = 0;
}
}
// 输出最后剩下的人
if (!list.isEmpty()) {
System.out.print(list.get(0));
}
}
}