⭐Introduction to Algorithms⭐Heap Medium 02 - LeetCode 703.Largest K element in data flow

Keywords: Algorithm leetcode

1. Title

1. Title Description

_Design a class that finds the kth largest element in the data stream. Note that the kth largest element is sorted, not the kth different element. Implement the KthLargest class:
_1) KthLargest(int k, int[] nums) initializes objects using integer k and integer stream nums.
_2) int add(int val) inserts Vals into the data stream nums and returns the k th largest element in the current data stream.
_Sample inputs: ['KthLargest','add','add','add','add','add','add', [[3,[4, 5, 8, 2], [3], [5], [10], [9], [4]]
_Sample output: [null, 4, 5, 5, 8, 8]

2. Infrastructure

  • The basic framework code given in the C language version is as follows:
typedef struct {

} KthLargest;

KthLargest* kthLargestCreate(int k, int* nums, int numsSize) {


int kthLargestAdd(KthLargest* obj, int val) {


void kthLargestFree(KthLargest* obj) {


3. Topic Link

Swordfinger Offer II 059.Largest K value of data flow
LeetCode 703.Largest K element in data flow

2. Problem-solving Report

1. Idea Analysis

_Maintain a small top heap, where elements are always maintained k k k, then the top of the heap must be the first k k Elements larger than k.

2. Time Complexity

_The process of creating a heap is O ( n l o g 2 n ) O(nlog_2n) O(nlog2 n), a pop-up is performed for each insert, and the time complexity of a single insert deletion is O ( l o g 2 n ) O(log_2n) O(log2​n).

3. Code Details

/**********************************Small Top Heap Template******************************************/
#define lson(idx) (idx << 1|1)
#define rson(idx) ((idx + 1) << 1)
#define parent(idx) ((idx - 1) >> 1)
#define root 0
#define DataType int

// Exchange of -1 and 1 becomes a big heap
int compareData(const DataType* a, const DataType* b) {
    if(*a < *b) {
        return -1;
    }else if(*a > *b) {
        return 1;
    return 0;

void swap(DataType* a, DataType* b) {
    DataType tmp = *a;
    *a = *b;
    *b = tmp;

typedef struct {
    DataType *data;
    int size;
    int capacity;

// Internal interface, lower case hump

// The heapShiftDown interface is an internal interface, so it is distinguished by lowercase humps to adjust for sinking while deleting elements from the heap.
void heapShiftDown(Heap* heap, int curr) {
    int son = lson(curr);

    while(son < heap->size) {
        if( rson(curr) < heap->size ) {
            if( compareData( &heap->data[rson(curr)], &heap->data[son] ) < 0 ) {
                son = rson(curr);                        // Always select nodes with smaller values
        if( compareData( &heap->data[son], &heap->data[curr] ) < 0 ) {
            swap(&heap->data[son], &heap->data[curr]);   // If the value of the child node is less than the parent node, the exchange is performed.
            curr = son;
            son = lson(curr);
        }else {
            break;                                       // The value of the child node is greater than that of the parent node, indicating that it is properly positioned, that the sink operation ends and that it jumps out of the cycle.

// The heapShiftUp interface is an internal interface, so it is distinguished by lowercase humps to adjust for the float when elements in the heap are inserted.
void heapShiftUp(Heap* heap, int curr) {
    int par = parent(curr);
    while(par >= root) {
        if( compareData( &heap->data[curr], &heap->data[par] ) < 0 ) {
            swap(&heap->data[curr], &heap->data[par]);   // If the value of the child node is less than the parent node, the exchange is performed.
            curr = par;
            par = parent(curr);
        }else {
            break;                                       // The value of the child node is larger than the parent node, indicating that it has been positioned correctly, the floating operation ends, and the cycle jumps out.

bool heapIsFull(Heap *heap) {
    return heap->size == heap->capacity;

// External interface, capitalized hump

// Empty heap
bool HeapIsEmpty(Heap *heap) {
    return heap->size == 0;

int HeapSize(Heap *heap) {
    return heap->size;

// Insertion of heap
// Insert in the last position and keep floating up
bool HeapPush(Heap* heap, DataType data) {
    if( heapIsFull(heap) ) {
        return false;
    heap->data[ heap->size++ ] = data;
    heapShiftUp(heap, heap->size-1);
    return true;

// Heap Delete
// 1. When deleting the top element of a heap, place the element with the largest subscript at the bottom of the heap on the top of the pair;
// 2. Then invoke shift Down to sink this element;
// For small-top heaps, the path from root to leaf must be monotonic, so the sink operation must end at some point in the path and ensure that all heap paths remain monotonic.
bool HeapPop(Heap *heap) {
    if(HeapIsEmpty(heap)) {
        return false;
    heap->data[root] = heap->data[ --heap->size ];
    heapShiftDown(heap, root);
    return true;

DataType HeapTop(Heap *heap) {
    return heap->data[root];

// Create Heap
Heap* HeapCreate(DataType *data, int dataSize, int maxSize) {
    int i;
    Heap *h = (Heap *)malloc( sizeof(Heap) );
    h->data = (DataType *)malloc( sizeof(DataType) * maxSize );
    h->size = 0;
    h->capacity = maxSize;

    for(i = 0; i < dataSize; ++i) {
        HeapPush(h, data[i]);
    return h;

// Destroy heap
void HeapFree(Heap *heap) {

/**********************************Small Top Heap Template******************************************/

typedef struct {
    Heap *heap;
    int K;
} KthLargest;

KthLargest* kthLargestCreate(int k, int* nums, int numsSize) {
    KthLargest *KL = (KthLargest *)malloc( sizeof(KthLargest) );
    KL->K = k;
    KL->heap = HeapCreate(nums, numsSize, 100000);  // (1)
    return KL;

int kthLargestAdd(KthLargest* obj, int val) {
    HeapPush(obj->heap, val);
    while(HeapSize(obj->heap) > obj->K) {           // (2)
    return HeapTop(obj->heap);

void kthLargestFree(KthLargest* obj) {

 * Your KthLargest struct will be instantiated and called as such:
 * KthLargest* obj = kthLargestCreate(k, nums, numsSize);
 * int param_1 = kthLargestAdd(obj, val);
 * kthLargestFree(obj);
  • ( 1 ) (1) (1) Create a small top heap;
  • ( 2 ) (2) (2) Keep the number of heap elements always equal k k k;

3. Small knowledge of the subject

_heap can be used for implementation K K K large number.

4. Notice for Adding Groups

_I believe most of my articles are "college students" and "elites" who can go to university, so we naturally want to "lean". If you are still a freshman, that's great. You have plenty of time. Of course, you can choose "brush opera". However, after "learning algorithms", three years you will naturally "not be in the same language".
_Then here, I have sorted out the classification of "dozens of basic algorithms" and click on Open:

🌌Guidelines to Getting Started with Algorithms🌌
_If the link is blocked or you have permission issues, you can chat with the author privately to resolve them.

_Overview of the general problem set:

_To make this interesting and to take care of beginners, only the simplest algorithm, Enumeration Series, is currently open (including linear enumeration, double pointer, prefix and, binary enumeration, three-thirds enumeration), when half of the members have finished brushing Enumeration Series.After all the questions, the next chapter opens, and when the set is finished and you're still in the group, you'll become a member of the Expert Group on the "Late Night People's Still Writing Algorithm".
_Don't underestimate this panel of experts. After three years, you'll be the last one to be seen. If you want to join, contact me. Considering that everyone is a student and that you don't have a "primary source of income", you won't ask for anything on your way to becoming God.
_🔥Contact the author, or sweep the 2-D code of the author's home page into groups, so join the list of brushing titles🔥

🔥Let the world have no hard-to-learn algorithms🔥
C language free animation tutorial, punch in with me! 🌞Guangtianhua Japanese Language C🌞
A Summary of C Language Topics at the Beginner Level 🧡100 Cases of Introduction to C Language🧡
Several kinematics learn a data structure 🌳Understanding Data Structure🌳
Group Learning, Group Growth 🌌Guidelines to Getting Started with Algorithms🌌
Competitor Golden Text Tutorial 💜Late Night Still Writing Algorithm💜

Posted by classic on Sat, 09 Oct 2021 12:21:15 -0700