360筆試題目-HashMap實現,360筆試-hashmap
自訂一個HashMap,實現map_put,map_delete,map_get方法,要求:
1.尋找時間複雜度O(1)
2..
3..
因為Java中內建HashMap,平時直接用,也沒有考慮,前一段時間只是實現了ArrayList,Vetor,Quene,並沒有考慮HashMap。筆試的時候由於時間緊,我只是在HashMap中定義兩個ArrayList,一個儲存Key,一個儲存Value,現在想想肯定是不對的,這根本沒有按照要求實現。題目的原意是讓實現鏈表,考察操作鏈結表的能力。回來之後,我想了想,用Java實現了一般的鏈表:
<span style="font-size:14px;">/** * * @author lip * 用拉鏈法實現hashMap * 原理:hashmap中有一個鏈表數組 * 一般數組的大小為一個素數 */public class HashMap<T1,T2>{ private final int LENGTH=31; private Entry<T1, T2>[]table; private int size=0;public HashMap(){table=new Entry[LENGTH];}//向hashMap插入值 public void put(T1 key,T2 value) { size++; //求出T1的hash值,然後p=hash(key)%LENGTH,將key放在數組中p位置處的鏈表中 //如果map中存在該值,那麼更新該值 //不存在該值,那麼插在鏈表最後一個位置 int pos=key.hashCode()%LENGTH; if(table[pos]==null) { table[pos]=new Entry<T1,T2>(key,value); return; } //遍曆list,看key-value是否已經存在 Entry<T1, T2> entry=table[pos]; boolean exist=false; while (table[pos] != null){if (table[pos].key == key)// 存在,更新就可以了{table[pos].value = value;size--;exist = true;break;}if(table[pos].next==null)break;else table[pos] = table[pos].next;} if(!exist) table[pos].next=new Entry<T1,T2>(key,value); table[pos]=entry; } //刪除一個key public void delete(T1 key) { int pos=key.hashCode()%LENGTH; Entry<T1, T2> entry=table[pos]; while(entry!=null) { if(entry.key==key) { //刪除當前接節點 Entry<T1, T2>tempEntry=entry.next; entry=entry.next; if(entry!=null) entry.next=tempEntry.next; size--; break; } entry=entry.next; } } //得到key的value public T2 getValue(T1 key) { int pos=key.hashCode()%LENGTH; Entry<T1, T2>entry=table[pos]; while(entry!=null) { if(entry.key==key) return entry.value; entry=entry.next; } return null; } //得到key的集合 public Set<T1> getKeySet() { Set<T1> set=new HashSet<T1>(); for(int i=0;i<LENGTH;i++) { Entry<T1, T2> entry=table[i]; while(entry!=null) { set.add(entry.key); entry=entry.next; } } return set; } //得到map的大小 public int size() { return size; }class Entry<T1,T2>{private T1 key;private T2 value;public Entry<T1, T2>next;public Entry(T1 key,T2 value){this.key=key;this.value=value;}}public static void main(String[] args){// TODO Auto-generated method stub HashMap<String, Integer>hashMap=new HashMap<String, Integer>(); hashMap.put("語文", 82); hashMap.put("數學", 99); hashMap.put("英語", 90); hashMap.put("物理", 88); hashMap.put("化學", 93); hashMap.put("生物", 86); hashMap.put("生物", 88); System.out.println("HashMap Size:"+hashMap.size()); System.out.println("生物:"+hashMap.getValue("生物")); System.out.println("語文:"+hashMap.getValue("語文")); Set<String> set=hashMap.getKeySet(); for(Iterator<String> iterator=set.iterator();iterator.hasNext();) { String key=iterator.next(); System.out.println(key+":"+hashMap.getValue(key)); }}}</span>運行