1. 程式人生 > 其它 >[簡單] 706. 設計雜湊對映

[簡單] 706. 設計雜湊對映

https://leetcode-cn.com/problems/design-hashset/

我會寫一些無腦得程式碼

class MyHashMap {


    class Node {
        int key;
        int value;

        Node(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public int getKey() {
            return key;
        }

        
public void setKey(int key) { this.key = key; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this
== o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; return key == node.key && value == node.value; } @Override public int hashCode() { return Objects.hash(key, value); } }
private int iSize = 16; Node[] arr = new Node[iSize]; int iListCount = 0; public MyHashMap() { } public void put(int key, int value) { if(iListCount + 1 > arr.length) { // 資料遷移; Node[] tempArr = new Node[arr.length]; for (int m = 0; m < arr.length; m++) { tempArr[m] = arr[m]; } iSize *= 2; arr = new Node[iSize]; // 拷貝回去. for (int m = 0; m < tempArr.length; m++) { arr[m] = tempArr[m]; } } boolean bExist = false; if(iListCount > 0) { for (int n = 0; n < iListCount; n++) { if(arr[n].getKey() == key) { bExist = true; // 進行值更新. arr[n].setValue(value); break; } } } if(!bExist) { arr[iListCount++] = new Node(key,value); } } public int get(int key) { int ret = -1; for (int n = 0; n < iListCount; n++) { if(arr[n].getKey() == key) { ret = arr[n].getValue(); break; } } return ret; } public void remove(int key) { int index = -1; for (int n = 0; n < iListCount; n++) { if(arr[n].getKey() == key) { index = n; break; } } if(index != -1) { List<Node> lst = new ArrayList<>();// Arrays.asList(arr); for (int n = 0; n < iListCount; n++) { lst.add(arr[n]); } lst.remove(index); arr = new Node[iSize]; for (int m = 0; m < lst.size(); m++) { arr[m] = lst.get(m); } iListCount--; } } }
View Code