import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
import java.util.Scanner;
/*
生成长度为n的int型随机数组,数组元素范围为0~n-1,每个元素都是唯一的。只使用基本数据类型。
*/
class Solution {
public static void rand(int[] arr, int n) {
for(int i = 0; i < n; i++) {
arr[i] = i;
}
//0 1 2 3 4...n-1
for (int i = arr.length-1; i > 0; i--) {
int r = new Random().nextInt(i+1);
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] arr = new int[n];
rand(arr, n);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
原文地址:https://www.cnblogs.com/Roni-i/p/12444898.html
时间: 2024-10-24 06:00:07