在一行中输入三个整数
,用空格隔开。
输出一个整数,表示最后剩下的"大王"编号。
5 1 2
3
初始队列编号为,从编号
开始报数:
出队,剩余
;
出队,剩余
;
出队,剩余
;
出队,剩余
,输出
。
import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//n个人
int n = in.nextInt();
//从编号为k的人开始报数(编号即数组下标)
int k = in.nextInt();
//报到m的人出队
int m = in.nextInt();
//初始化队列
List<Integer> people = new ArrayList<>();
for (int i = 0; i < n; i++) {
people.add(i);
}
int currentIndex =
k; //每次开始报数的人的下标,动态的、变化的。
while (people.size() > 1) {
//这个公式很关键,当前坐标+步数m-1 即是要移除的数的下标。 %是为了避免下标越界同时保证到最后一个数的时候环形遍历【核心!取模具有天然的环形遍历特性】
//比如5个人,m=6,k=1 那么removeIndex=1+6-1=6,下标越界!6%5=1 则刚好吻合从下标1开始走6步到1。
int removeIndex = (currentIndex + m - 1) % people.size();
people.remove(removeIndex);
//分2种情况:1、如果移除的数在最后一个数左侧,那么currentIndex=removeIndex; 2、如果移除的数是最后一个数,那么currentIndex会下标越界。
//比如 0 1 3 4 ==> 0 1 3的过程,4被移除后,此时currentIndex=removeIndex=3,那么3在0 1 3 里开始重新计数会越界?怎么办?也会靠取模
currentIndex = removeIndex % people.size();
// System.out.println("当前队列:" + JSON.toJSONString(people));
}
System.out.println(people.get(0));
}
} import java.util.*;
public class Main{
public static void main(String[] args){
int n,k,m;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
m = in.nextInt();
List<Integer> list = new ArrayList<>();
for(int i=0;i<n;i++)list.add(i);
while(true){
if(list.size()==1)break;
if(k+m-1>list.size()-1){
int len = list.size();
list.remove((k+m-1)%list.size());
k = (k+m-1)%len;
}else{
list.remove(k+m-1);
k = k+m-1;
}
}
System.out.println(list.get(0));
}
} import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n=in.nextInt(), k=in.nextInt(), m=in.nextInt();
StringBuffer sb = new StringBuffer();
for (int i=0; i<n; i++) {
sb.append(i);
}
while (sb.length()!=1) {
k+=m;
if (k>sb.length()) {
k=k%m;
}
sb.deleteCharAt(k-1); // 从自己开始数,所以减一
}
System.out.println(sb);
}
} 还是喜欢用StringBuffer