The algorithm sequentially outputs numbers from 1 to 100, which are required to be random and cannot be repeated

The title is: There are numbers from 1 to 100, the data output each time is random and cannot be repeated, and the time complexity is O(n).

answer:

Here is where the reverse loop begins

    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++;
        }
    }

The above code can run correctly.

insert image description here

But if you write as follows, you will get an error, here is the cycle from 1 to 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++;
        }
    }

insert image description here

Guess you like

Origin blog.csdn.net/admin_jalen/article/details/123762761
Recommended