左神演算法學習筆記基礎篇(7) 雜湊函式

2021-09-28 13:37:26 字數 807 閱讀 8458

設計一種結構,在該結構中有三個功能:

insert(key):將某個key加入到該結構,做到不重複加入。

delete(key):將原本在結構中的某個key移除。

getrandom():等概率隨機返回結構中的任何乙個key。

**要求:**這三個功能的時間複雜度都為o(1)

建立兩張雜湊表

map1

map2

keystring

interger

value

integer

string

對於insert函式,只需要先判斷雜湊表中是否含有該key,若無,呼叫hashmap的put方法即可。

對於delete函式,刪除了雜湊表中的某一鍵值對後,只需要將最後一組鍵值對補充到刪除的缺口上即可。

注:hashmap的put方法,若以前已包含了鍵值對,則替換圓鍵值對。

getrandom函式,(int)math.random()*mapsize可以在0~size-1中隨機生成乙個數。

public

static

class

randompool

public

boolean

insert

(string str)

return

false;}

public

void

delete

(string str)

}public string getrandom()

}

左神演算法學習日記 堆(一)

一直覺得赫夫曼樹沒什麼diao用,沒想到這道題可以用赫夫曼樹,而且用小根堆可以實現赫夫曼樹,學到好多。題目二一塊金條切成兩半,是需要花費和長度數值一樣的銅板的。比如長度為20的金條,不管切成長度多大的兩半,都要花費20個銅板。一群人想整分整塊金條,怎麼分最省銅板?例如,給定陣列,代表一共三個人,整塊...

左神演算法學習日記 堆(二)

include include include include include include include includeusing namespace std class project project const project p push進堆時用到了拷貝建構函式,雖然不寫也無所謂 pro...

左神演算法學習日記 樹dp

樹dp問題只需要考慮每個結點的所有孩子的情況就可以解決 class node node class treeinf void creat node node if r 獲得子樹中結點最多的搜尋二叉樹的結點個數 treeinf getmaxnode node node treeinf leftinf ...