OOD + 數據結構實現

Design HashMap https://www.kancloud.cn/digest/pieces-algorithm/163623 https://blog.csdn.net/Thousa_Ho/article/details/73065017 核心: hash函數的實現 int idx(int key) { return Integer.hashCode(key) % nodes.length; 採用了除餘法計算hash值,這種方法選擇的m應當使得散列函數值儘量與key的各個位數的bit都有關,最好爲素數,若是m是key的冪次,那麼就等於只用到了key的低位java

class MyHashMap {
    class ListNode {
        int key, val;
        ListNode next;
        
        ListNode(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    final ListNode[] nodes = new ListNode[1000];

    /** Initialize your data structure here. */
    public MyHashMap() {
        
    }
    
    /** value will always be non-negative. */
    public void put(int key, int value) {
        int i = idx(key);
        if (nodes[i] == null) {
            nodes[i] = new ListNode(-1, -1);
        }
        ListNode prev = find(nodes[i], key);
        if (prev.next == null) {
            prev.next = new ListNode(key, value);
        } else {
            prev.next.val = value;
        }
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    public int get(int key) {
        int i = idx(key);
        if (nodes[i] == null) {
            return -1;
        }
        ListNode node = find(nodes[i], key);
        return node.next == null ? -1 : node.next.val;
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    public void remove(int key) {
        int i = idx(key);
        if (nodes[i] == null) return;
        ListNode prev = find(nodes[i], key);
        if (prev.next == null) return;
        prev.next = prev.next.next;
    }
    
    int idx(int key) {
        return Integer.hashCode(key) % nodes.length;
    }
    
    // find the value map to the key
    ListNode find(ListNode bucket, int key) {
        ListNode node = bucket;
        ListNode prev = null;
        while (node != null && node.key != key) {
            prev = node;
            node = node.next;
        }
        return prev;
    }
}
複製代碼

Heap的實現node

  • Complete Binary Tree:數組

  • Each Level, except(possibly) last, compeletely filled with nodesapp

  • Last Level: nodes filled from left to right函數

  • Heap Property:this

  • Complete Bininary Treespa

  • Heap property: each node has a smaller(larger) that that of either of its children.net

  • Left child may have smaller or larger timestamp compared to the right child指針

Globalcode

Delete 和 Insert都是三步走, 以最小堆爲例

Delete Operation:

  1. Remove root
  2. Move "last" node to root
  3. Migrate root down tree as far as necessary to maintain heap property

Insert Operation:

  1. Insert node to next availabel node in last level
  2. Move node up toward root preserving the heap property

使用數組實現能夠避免指針的使用,由於對於節點i的left child就是2i + 1, right child就是2i + 2

2i 位運算中的左移操做 (i << 1)

相關文章
相關標籤/搜索