生成N位不重複的隨機數
阿新 • • 發佈:2018-12-06
package com.jack.question.random; import java.util.Arrays; import java.util.Random; /** * @author lvh */ public class RandomArray { /* * 如題,定義一個100個元素的陣列arr[100]; * 把隨機產生的1-100之間的不重複的100個隨機數存放到此陣列中,怎樣產生隨機數才能效率高 */ public static int[] getRandomNum1(int n) { int[] data = new int[n]; Random random = new Random(); int num; boolean bool = false; int arrayIndex = 0; while(arrayIndex < n) { num = random.nextInt(n); bool = false; //for(int x = 0, len = arrayIndex; x < len; x++) { for(int x = 0, len = arrayIndex; x < len; x++) { //從連結串列頭到連結串列尾查詢這個值, 時間複雜度O(N^2) if(data[x] == num) { bool = true; break; } } if(!bool) { data[arrayIndex] = num; arrayIndex++; } } return data; } public static int[] getRandomNum2(int n) { int[] input = new int[n]; Random random = new Random(); for(int x = 0 ; x < n ; x ++) { input[x] = x; } int[] out = new int[n]; int randomIndex ; int arrayLen = n; for(int x = 0; x < n ; x++) { randomIndex = random.nextInt(arrayLen); out[x] = input[randomIndex]; //刪除元素,後面的元素前移一位 for(int y = randomIndex; y < n - 1; y++) { input[y] = input[y+1]; } arrayLen--; } return out; } //時間複雜度O(n) public static int[] getRandomNum3(int n) { int[] input = new int[n]; Random random = new Random(); for(int x = 0 ; x < n ; x ++) { input[x] = x; } int[] out = new int[n]; int randomIndex ; int arrayLen = n; for(int x = 0; x < n ; x++) { randomIndex = random.nextInt(arrayLen); out[x] = input[randomIndex]; //有效數字前移 if(randomIndex != arrayLen - 1) { input[randomIndex] = input[arrayLen - 1]; } arrayLen--; } return out; } public static void main(String[] args) { int num = 30000; long begin1 = System.currentTimeMillis(); getRandomNum1(num); long end1 = System.currentTimeMillis(); System.out.println(end1 - begin1); long begin2 = System.currentTimeMillis(); getRandomNum2(num); long end2 = System.currentTimeMillis(); System.out.println(end2 - begin2); long begin3 = System.currentTimeMillis(); getRandomNum3(num); long end3 = System.currentTimeMillis(); System.out.println(end3 - begin3); } }