![](/img/trans.png)
[英]How to insert multiple keys with the same value into a hash map in Java?
[英]Finding n keys that all hash to same hash value
給出的哈希函數:
public int hash4(int k) {
Random rand = new Random(k);
return rand.nextInt(size);
}
目標是找到n(size)個鍵(k),這些鍵使用此哈希函數哈希為相同的哈希值(引起沖突)。 Size是用戶傳遞的常數,並且大小永遠不會大於1000。鍵可以是的最大值是n ^ 2,並且不能一遍又一遍地使用相同的鍵。 任何幫助,將不勝感激!
我試圖解決這個問題的方法是使用數字1-n作為鍵從1循環到n,尋找模式。
假設有n個帶有n 2個鍵的存儲桶,使用信鴿原理 ,我們知道一個存儲桶至少具有n個鍵
為了解決這個問題,我們需要遍歷所有鍵
int keys = n * n;
for(int i = 0; i < keys; i++)
接下來,我們將查看哪些鍵發生碰撞是針對每個碰撞組將每個鍵存儲在列表/集中
List<List<Integer>> collisions = new ArrayList<List<Integer>>(n);
for(int i = 0; i < n; i++)
collisions.add(new LinkedList<Integer>());
collisions.get(hash(key)).add(key);
一旦我們有了所有的碰撞,就很容易找到至少有n次碰撞的列表
for(List<Integer> collision : collisions)
if(collision.size() >= n)
return collision; //or just print
全部放在一起...
List<Integer> findCollisions(int n)
{
List<List<Integer>> collisions = new ArrayList<List<Integer>>(n);
for(int i = 0; i < n; i++)
collisions.add(new LinkedList<Integer>());
int keys = n * n;
for(int i = 0; i < keys; i++)
collisions.get(hash(i)).add(i);
for(List<Integer> collision : collisions)
if(collision.size() >= n)
return collision;
return null; //this should never happen, due to pigeonholes, but compiler doesn't know
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.