1

我试图弄清楚下面函数的复杂性。我猜这将是 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 之间。

4

1 回答 1

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)
于 2012-09-06T05:07:52.350 回答