左神算法學習筆記基礎篇(7):哈希函數

利用哈希函數設計RandomPoll實現增刪查

1.題目

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

  1. insert(key):將某個key加入到該結構,做到不重複加入。
  2. delete(key):將原本在結構中的某個key移除。
  3. getRandom():等概率隨機返回結構中的任何一個key。

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

2.算法思路

建立兩張哈希表

map1 map2
key String Interger
value Integer String
  1. 對於insert函數,只需要先判斷哈希表中是否含有該key,若無,調用HashMap的put方法即可。
  2. 對於delete函數,刪除了哈希表中的某一鍵值對後,只需要將最後一組鍵值對補充到刪除的缺口上即可。
    注: HashMap的put方法,若以前已包含了鍵值對,則替換圓鍵值對。
  3. getRandom函數,(int)Math.random()*mapSize可以在0~size-1中隨機生成一個數。

3.算法代碼

public static class RandomPool{
        HashMap<String,Integer> map1;
        HashMap<Integer,String> map2;
        int mapSize;
        public RandomPool(){
            map1 = new HashMap<String,Integer>();
            map2 = new HashMap<Integer,String>();
            mapSize = 0;
        }
        public  boolean insert(String str){
            if(!map1.containsKey(str)){
                map1.put(str,++mapSize);
                map2.put(mapSize,str);
                return true;
            }
            return false;
        }

        public void delete(String str){
            if(map1.containsKey(str)){
                int deleteIndex = map1.get(str);
                int lastIndex = --mapSize;
                map1.put(map2.get(lastIndex),deleteIndex);	//map1中用最後一組鍵值對填充被刪掉鍵值對的位置
               map2.put(deleteIndex,map2.get(lastIndex));	////map1中用最後一組鍵值對填充被刪掉鍵值對的位置
                
                map1.remove(str);
                map2.remove(lastIndex);	 //把最後一組鍵值對刪除,因爲該鍵值對已經拿去填充了

            }
        }

        public String getRandom(){
            return map2.get((int)Math.random()*mapSize);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章