タイトルは: 1 から 100 までの数字があり、毎回出力されるデータはランダムであり、繰り返すことはできず、時間の複雑さは O(n) です。
答え:
ここから逆ループが始まります
public static int N = 100;
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= N; i++) {
list.add(i);
}
int size = list.size();
int count = 0;
for (int j = size; j > 0; j--) {
int index = new Random().nextInt(j);
int value = list.get(index);
System.out.println("随机位置:" + index + "--对应的数据:" + value + "--当前循环次数:" + count);
list.remove(index);
count++;
}
}
上記のコードは正しく実行できます。
ただし、次のように記述するとエラーが発生します。ここでは、1 から N までのサイクルを示します。
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= N; i++) {
list.add(i);
}
int count = 0;
for (int j = 1; j < N; j++) {
int index = new Random().nextInt(j);
int value = list.get(index);
System.out.println("随机位置:" + index + "--对应的数据:" + value + "--当前循环次数:" + count);
list.remove(index);
count++;
}
}