Java 洗牌函数复杂性

Java 洗牌函数复杂性,java,random,hashmap,complexity-theory,big-o,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{

我正试图找出下面函数的复杂性。我猜应该是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);
}
HashMap value=newhashmap();


对于(int i=0;我不太明白你在说什么。你是说它是O(n^2)吗?在HashMap中查找随机值不应该取O(n),因为containsKey方法是O(1)你是如何处理冲突的?我想我不会有冲突。因为我要添加的键是数组的索引。我可以确定不会有任何重复项。If values.containsKey(random)如果为true,则我不会将该索引添加到HashMap。因此,我不会两次添加同一个键。检查新的随机值是否在数组中会使O(n)你认为呢?我已经添加了数组的长度和随机数的范围。我同意检查生成的数字是否不在HashMap中会增加复杂性,但我希望它在O(nlogn)左右。我不太明白你在说什么。你是说它是O(n^2)?在HashMap中查找随机值不应该花费O(n)因为containsKey方法是O(1)你是如何处理冲突的?我想我不会有冲突。因为我添加的键是数组的索引。我可以确定不会有任何重复。如果值。containsKey(随机)如果为true,则我不会将该索引添加到HashMap。因此,我不会两次添加同一个键。检查新的随机值是否在数组中会使O(n)你认为呢?我已经添加了数组的长度和随机数的范围。我同意复杂性会增加,以检查生成的数是否不在HashMap中,但如果α非常小并且接近O(n),我预计它将在0(nlogn)左右。关于冲突呢?查找映射没有的随机值是O(n)想想随机整数的范围和映射大小。假设它是4/3-->,那么查找不存在的随机值将是%66-->对每个新元素执行此操作将建立O(n)(我们可以忽略hashmap查找的O(1))更新了答案,但找不到logn。你认为logn来自哪里?没关系,我认为你是对的。复杂度可能会变成n^2。我可以使用什么算法来洗牌复杂度低于此的排序数组?当然,如果α非常小,并且接近O(n)。关于冲突呢?查找映射没有的随机值是O(n)想想随机整数的范围和映射大小。假设它是4/3-->,那么查找不存在的随机值将是%66-->对每个新元素执行此操作将建立O(n)(我们可以忽略hashmap查找的O(1))更新了答案,但找不到logn。你认为logn来自哪里?没关系,我认为你是对的。复杂度可能会变成n^2。我可以使用什么算法来洗牌复杂度低于此的排序数组?
 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)