生成N位不重复的随机数

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

}

猜你喜欢

转载自blog.csdn.net/winer1220/article/details/50455652