Java兩種方法實現循環報數


問題描述:

十個猴子圍成一圈選大王,依次1-3 循環報數,報到3 的猴子被淘汰,直到最后一只猴子成為大王。問,哪只猴子最后能成為大王?

方法一:Java鏈表

public class TestAll {

static Scanner scanner = new Scanner(System.in);
static int num;
static String str;
static LinkedList<String> list = new LinkedList<String>();
static LinkedList<String> result = new LinkedList<String>();

public static void main(String[] arg) {
input();
output();
}

private static void output() {
pushNum();
Iterator it = result.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
}

private static void pushNum() {
int i = 1;
while (list.size() > 0) {
// System.out.println(i+"!! ");
Iterator it = list.iterator();
while (it.hasNext()) {
String node = (String) it.next();
if (i == num) {
result.add(node);
it.remove();
i = 0;
}
i++;
}
}

}

private static void input() {
str = scanner.nextLine();
String[] tmp = str.split(" ");
num = Integer.parseInt(tmp[0]);
for (int i = 1; i < tmp.length; i++) {
list.add(tmp[i]);
}

}
}

方法二:數組

public class TimeTest {
public static void main(String[] args) {
int num = 10;
boolean[] array = new boolean[num];
for (int i = 0; i < num; i++) {
array[i] = true;
}
int index = 0;
int count = 0;
int n = num;
while (n > 1) {
if (array[index] == true) {
count++;
if (count == 3)
// 當count等於3時,就淘汰一個;
{
array[index] = false;
n--; // 當有一個被淘汰時,n--;
count = 0;
}
}
index++;
// 當從0循環到29時,重新置index為0;
if (index == num) {
index = 0;
}
}
for (int i = 0; i < num; i++) {
if (array[i] == true)
System.out.println(i + 1);
}
}
}

 其中方法一的時間復雜度為O(n^2)

方法二的時間復雜度為O(n)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM