特殊的完全二叉树

所有节点大于等于它的子节点

JS中常用数组表示堆

- 左侧子节点:2*index+1;

- 右侧子节点:2*index+2

- 父节点:(index-1)/2

用处:快速找出最大值最小值;找出第K个最大最小元素;

// #### 堆
// 特殊的完全二叉树
// 所有节点大于等于它的子节点JS中常用数组表示堆

// - 左侧子节点:2*index+1;
// - 右侧子节点:2*index+2
// - 父节点:(index-1)/2

// 用处:快速找出最大值最小值;找出第K个最大最小元素;

class Minheap{
    constructor(){
        this.heap = [];
    }
    swap(i1, i2){
        const temp = this.heap[i1];
        this.heap[i1] = this.heap[i2]
    }
    //获取父节点
    getParentIndex(i){
        // return Math.floor((i-1)/2)
        return (i-1) >> 1;
    }
    getLeftIndex(i){
        return i * 2 + 1;
    }
    getRightIndex(i){
        return i * 2 + 2;
    }
    //交换
    swap(i1,i2){
        const temp = this.heap[i1];
        this.heap[i1] = this.heap[i2];
        this.heap[i2] = temp;
    }
    //上移
    shiftUp(index){
        const parentIndex = this.getParentIndex(index);
        if(this.heap[parentIndex]> this.heap[index]){
            this.swap(parentIndex,index);
            this.shiftUp(parentIndex);
        }
    }
    //下移
    shiftDown(index){
        const leftIndex = this.getLeftIndex(index);
        const rightIndex = this.getRightIndex(index);
        if(this.heap[leftIndex]<this.heap[index]){
            this.swap(leftIndex,index);
            this.shiftDown(leftIndex);
        }
        if(this.heap[rightIndex]<this.heap[index]){
            this.swap(rightIndex,index);
            this.shiftDown(rightIndex);
        }
    }
    insert(value){
        this.heap.push(value);
        this.shiftUp(this.heap.length-1);
    }
    pop(){
        this.heap[0] = this.heap.pop();
        this.shiftDown(0);
    }
    //获取堆顶
    peek(){
        return this.heap[0];
    }
    size(){
        return this.heap.length;
    }
}

const h = new Minheap();
h.insert(3);
h.insert(2);
h.insert(1);
h.pop();
// https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
// https://leetcode-cn.com/problems/merge-k-sorted-lists/
posted @ 2021-12-13 22:17  三千山人  阅读(26)  评论(0编辑  收藏  举报