題目是: 有1~100的數(shù)字,每次輸出的數(shù)據(jù)都是隨機的不能重復(fù),時間復(fù)雜度在O(n).
解答:
這里是反向循環(huá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 + "--對應(yīng)的數(shù)據(jù):" + value + "--當(dāng)前循環(huán)次數(shù):" + count);
list.remove(index);
count++;
}
}
上述代碼可以正確運行完成。

image.png
但是如果按照下面的寫法是會報錯的, 這里是從1到N開始循環(huá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 + "--對應(yīng)的數(shù)據(jù):" + value + "--當(dāng)前循環(huán)次數(shù):" + count);
list.remove(index);
count++;
}
}

image.png