Test instructions: Randomly generates 100 numbers in 1-10000, 1-10000 is already in the array and requires O (1) for both time and space.
Idea: Because the space to O (1), so we can think of this must be in the original array based on the operation, time also to O (1) words, prove that we can not hash after the sentence. So we can use a pointer to represent the currently generated random number, then the pointer from 1, each time from the rest of the number of random one and the current pointer Exchange can be completed, wrote the code, the wrong to point out.
import Java.util.arraylist;import java.util.hashset;import Java.util.random;import Java.util.set;public class Solution { Private int[]a = new int[10000+5]; {for (int i = 1; I <= 10000; i++) a[i] = i;} Private random Rand = new Random (ublic);p arraylist<integer> Rand100 () {arraylist<integer> ans = new Arrayli St<integer> (); int index = 1;for (int i = 1; I <= 10000; i++) {int ind = index + rand.nextint (10000-index+1); int T MP = A[index];a[index] = A[ind];a[ind] = Tmp;ans.add (A[index]); index++;} return ans;} public static void Main (string[] args) {arraylist<integer> list = new solution (). Rand100 (); for (int i:list) System.out.println (i); set<integer> set = new hashset<integer> (list); for (int i = 1; i <=; i++) {if (set.contains (i) = = False) {System.out.println (false); Break } } }}
Randomly generate 100 numbers in 1-10000