Database - priority queue (heap of application) (plus TOPK interview questions often test questions)

A concept

   In many applications, we often need to be treated as priority cases for processing transactions, such as the highest priority of the first object, and then deal with the second highest object. In this case, our data structure should provide two basic operations, a highest priority is to return the object, a new object is added. This data structure is a priority queue (Priority Queue)

Two . Priority queue implementation - heap

Three operation

   1. queues (with a small stack example)

      <1. The array element in the array is inserted into the end of play

      <2 Comparison with values ​​parent node, than he is not movable; younger, and exchange

      <3. Above operation is continued until reaching the root node

     Code:

public void offer(int i) {
     array[size++]=i;//因为插入元素的下标位置为数组末尾即size处,且插入后size需要加加
     shiftUpSmall(array,size-1);
}//入队 插入元素 当前的堆尾 进行小堆的向下调整

   2. the queue (for example in a small pile) (delete elements) 

     <1. Because the element directly to the top of the tree, then the rest of the tree will not balance it needs to be exchanged

     <2. The last element of the current top of the tree and the tree is exchanged, and then proceeds to the top of the tree to the new heap small adjustments

    Code:

   public int poll(){
        int element=array[0];
        array[0]=array[--size];//先减减 在使用 获取当前队尾下标 出队之后整体元素数减1
        Heap.shiftDownSmall(array,size,0 );//使用小堆来建立新堆
        return element;
    }//出队
    //将当前堆的最后一个元素与要出堆的元素(堆顶)进行交换 输出
    //对当前堆顶进行小堆向下调整

    3. Return to the first team element (direct return to) (do not delete)

    Code:

    public int peek(){
        return array[0];
    }//返回队首元素(不删除)

IV. Two Incorrect handling of different return values

       Error handling thrown returns the special value

       Queues add (e) offffer (e)

       A queue remove () poll ()

       Team first element element () peek ()

Five .TOPK problem (focus)

TOPK问题(从海量数据中找到k个最大的)
    操作:从数组中取k个元素,建立一个小堆。堆顶为这几个数 中最小的元素,将数组中的剩余元素依次与其比较,比堆顶小的元素坑定比堆内所有元素都小,如果大于堆顶 则取代当前堆顶,并进行小堆的调整。持续直至最后一个元素
    伪代码:
    heap[k]=createHeapBig(arr[1,k]);
    for(i=k+1;i<array.length;i++){
         shiftDownSmall(heep[k],array.length-k,arr[i]);
    }
    returnheap[k];

 

Published 40 original articles · won praise 4 · Views 868

Guess you like

Origin blog.csdn.net/weixin_44919969/article/details/101564409