随机函数复杂性

时间:2012-09-06 05:03:20

标签: java random hashmap complexity-theory big-o

我想弄清楚下面这个函数的复杂性。我猜它会是O(n),因为Random类在O(1)中产生一个随机数,put()和containsKey()也是O(1)。

但是由于循环中有do-while,我不确定复杂性是否会改变,因为如果值包含在HashMap中,则random()可以被多次调用。我将不胜感激任何帮助!

HashMap<Integer, Integer> values = new HashMap();
for(int i=0 ; i<a.length; i++){
    do{
        // set variable random to some integer between 0 and a.length using Random class in Java, 0 is included. 
    }while(values.containsKey(random) == true);
    b[i] = a[random]
    values.put(random,0);
}

数组的长度约为1000,生成的随机数为0到999.

1 个答案:

答案 0 :(得分:1)

 Building the map elements: O(n)--->for loop

 Checking if the random value is in the map: O(1+α) with a good hash function
 Trying to find a random value which your map does not have: O(n)
 (because you are using integer. Even floats would give very good resolution)


 array length=1000, random-value range=1000(from 0 to 999)
 think you are at the last element. probability of getting proper value is:
 %0.1 which takes an average of 1000 trials only for the last element (n)
 nearly same for the (n-1)st element (%0.2-->n/2 trials)
 still nearly same for (n-2)nd element (%0.3-->n/3 trials)

 what is n+n/2 + n/3 + n/4 + n/5  ... + 1 = a linear function(O(n)) +1 
 α2=1 but neglecting :) and this is on top of a O(n)


 Result: O(n*n+α*n*n) close to O(n*n)