解题思路:循环实现,将数组模拟成一个圈
注意事项:大佬帮忙看看优化,指正思路;
参考代码:
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
// 有n人围成一圈,顺序排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位。
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int []arr = new int[n];
for (int i = 1; i <= arr.length; i++) {
arr[i-1] = i;
}
int[] c = c(arr);
System.out.println(c[0]);
}
public static int[] a(int []arr,int len){
for (int i = 2; i <= arr.length-len; i+=3) {
arr[i] = 0;
}
return arr;
}
public static int[] b(int []ra,int []b ){
for (int i = 0; i < ra.length; i++) {
System.out.print("ra:"+ra[i]+" ");
}
System.out.println();
for (int i = 0; i < b.length; i++) {
System.out.print("b:"+b[i]+" ");
}
System.out.println();
int len = ra.length-(ra.length/3);
System.out.println("len:"+len);
int []arr = new int[len];
if(ra.length%3==0){
int index = 0;
for (int i = 0; i < ra.length; i++) {
if (ra[i] != 0) {
arr[index] = ra[i];
index++;
}
}
}else {
for (int i = 0; i < b.length; i++) {
arr[i] = b[i];
}
int index = 0;
for (int i = 0; i < ra.length-b.length; i++) {
if(ra[i]!=0){
arr[index+ b.length]=ra[i];
index++;
}
}
}
if (arr.length==2) {
int []arr1 = {arr[1]};
return arr1;
}else {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
return arr;
}
}
public static int[] c(int []arr){
if(arr.length==1){
return arr;
}
int len = arr.length % 3;
int[] ra = a(arr, len);
if(len==0){
int [] a = new int[2];
int bIndex = 0;
for (int i = arr.length-3; i < arr.length-1; i++) {
a[bIndex] = arr[i];
bIndex++;
}
return c(b(ra,a));
}else {
int [] b = new int[len];
int bIndex = 0;
for (int i = arr.length-len; i < arr.length; i++) {
b[bIndex] = arr[i];
bIndex++;
}
return c(b(ra,b));
}
}
}
0.0分
3 人评分
C语言程序设计教程(第三版)课后习题6.1 (C语言代码)浏览:650 |
C二级辅导-统计字符 (C语言代码)浏览:528 |
程序员的表白 (C语言代码)浏览:706 |
C语言程序设计教程(第三版)课后习题6.5 (C语言代码)浏览:616 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:701 |
C语言训练-亲密数 (C语言代码)浏览:697 |
循环入门练习5 (C语言代码)浏览:907 |
1035 题解浏览:875 |
蛇行矩阵 (C语言代码)浏览:559 |
勾股数 (C语言代码)浏览:830 |