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)

相关文章
相关标签/搜索