Algorithms and Data Structures base - heap (Heap) and a priority queue (Priority queue)

Pile foundation

Heap (Heap) is a data structure having such properties: 1/2 value of a complete binary tree / all nodes than (less than or equal to) the value of the child node:

Source: here

Stack may store an array, insertion, deletion will trigger node shift_down, shift_up operation, the time complexity of O (logn).

The heap is a priority queue (Priority queue) of the underlying data structure, a priority queue more frequently used instead of directly using the heap handling problems. Using the properties of the stack can easily obtain extremum, e.g. LeetCode subject 215. Kth Largest Element in an Array, the time complexity of O (nlogn):

    //215. Kth Largest Element in an Array
    int findKthLargest(vector<int>& nums, int k) {
//默认为大顶堆,等同于 priority_queue<int,vector<int>,less<int>> q; priority_queue
<int> q(nums.begin(),nums.end()); for(int i=0;i<k-1;i++) q.pop(); return q.top(); }

 

LeetCode related questions:

703. Kth Largest Element in a Stream  题解

295. Find Median from Data Stream  题解

 

 

The top node eleven removed, heap sort can be realized, for example, the classic subject 23. Merge k Sorted Lists, with priority queue computation time complexity is O (nlogk), n is the total number of elements, k is the number of list.

 

LeetCode related questions:

23. Merge k Sorted Lists  题解

 

Custom priority

For the priority queue, we can customize priority criteria, such as elemental frequency, distance, cost and the like. Then we need to customize the priority queue of comparison method:

    struct compare{
        bool operator()(const pair<char,int> a,const pair<char,int> b){
            return b.second > a.second;
        }  
    };
    //priority_queue<Type, Container, Functional>
    priority_queue<pair<char,int>,vector<pair<char,int>>,compare> pq;

 

LeetCode related questions:

451. Sort Characters By Frequency  题解

347. Top K Frequent Elements   solution to a problem

692. Top K Frequent Words   explanations

973. K Closest Points to Origin  题解

767. Reorganize String  题解

 

Priority queue and greed

It can be easily achieved by a priority queue extremes, and extremes in itself embodies the idea of ​​greed (Greedy); and greedy when used in problem-solving ideas, consider using a priority queue can get extremes.

 

LeetCode related questions:

1046. Last Stone Weight  题解

253. Meeting Rooms II   solution to a problem

871. Minimum Number of Refueling Stops  题解

502. IPO   solution to a problem

 

Priority queue and BFS

In the algorithms and data structures base - a queue (Queue) describes the common queue analog breadth-first search (BFS) process, as a special priority queue queues, the BFS also be used, in order to implement the search of the priority neighbor node.

 

LeetCode related questions:

778. Swim in Rising Water  题解

 

 

Guess you like

Origin www.cnblogs.com/bangerlee/p/11205539.html