題目是: 有1~100的數(shù)字冤荆,每次輸出的數(shù)據(jù)都是隨機(jī)的不能重復(fù)参咙,時(shí)間復(fù)雜度在O(n).
解答:
這里是反向循環(huán)開(kāi)始
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("隨機(jī)位置:" + index + "--對(duì)應(yīng)的數(shù)據(jù):" + value + "--當(dāng)前循環(huán)次數(shù):" + count);
list.remove(index);
count++;
}
}
上述代碼可以正確運(yùn)行完成缆毁。
但是如果按照下面的寫(xiě)法是會(huì)報(bào)錯(cuò)的甩十, 這里是從1到N開(kāi)始循環(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("隨機(jī)位置:" + index + "--對(duì)應(yīng)的數(shù)據(jù):" + value + "--當(dāng)前循環(huán)次數(shù):" + count);
list.remove(index);
count++;
}
}