算法 依次輸出1到100的數(shù)字 要求隨機且不能重復(fù)

題目是: 有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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容