239. 滑动窗口最大值 Sliding Window Maximum

题目 <https://leetcode-cn.com/problems/sliding-window-maximum/>

用堆来求,同时记录下index,如果堆顶的index在范围外,则出堆

struct HeapNode{
    int index;
    int val;
};

struct Heap{
    struct HeapNode *heap_val;
    int len;
    int cap;
};

struct Heap * heap_create(int cap){
    struct Heap *heap = malloc(sizeof(struct Heap));
    heap->len = 0;
    heap->cap = cap;
    heap->heap_val = malloc(sizeof(struct HeapNode) * cap);
    return heap;
}

void heap_push(struct Heap *heap,struct HeapNode *heap_node){
    int child = heap->len,parent;

    parent = (child-1)/2;
    while(child != 0 && heap_node->val > heap->heap_val[parent].val){
        heap->heap_val[child] = heap->heap_val[parent];
        child = parent;

        parent = (child-1)/2;
    }
    heap->heap_val[child] = *heap_node;
    heap->len++;
}


void heap_pop(struct Heap *heap){
    struct HeapNode heap_node = heap->heap_val[heap->len-1];
    heap->len--;


    int parent = 0,child;
    child = parent*2+1;
    while(child<heap->len){//注意是判断child
        if(child+1 < heap->len && heap->heap_val[child+1].val > heap->heap_val[child].val){
            child++;
        }

        if(heap->heap_val[child].val > heap_node.val){
            heap->heap_val[parent] = heap->heap_val[child];
            parent = child;
            child = parent*2+1;
        }else{
            break;
        }
    }
    heap->heap_val[parent] = heap_node;
}

void heap_peek(struct Heap *heap,struct HeapNode *heap_node){
    *heap_node = heap->heap_val[0];
}

void heap_free(struct Heap *heap){
    free(heap->heap_val);
    free(heap);
}

int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
    if(k == 1){
        *returnSize = numsSize;
        return nums;
    }

    int *returnNums = malloc(sizeof(int) * (numsSize-k+1));
    int returnLen = 0;

    struct Heap * heap = heap_create(numsSize);
    struct HeapNode heap_node;
    int i;
    for(i=0;i<k;i++){
        heap_node.index = i;
        heap_node.val = nums[i];
        heap_push(heap,&heap_node);
    }
    heap_peek(heap,&heap_node);
    returnNums[returnLen++] = heap_node.val;

    for(i=k;i<numsSize;i++){
        heap_node.index = i;
        heap_node.val = nums[i];
        heap_push(heap,&heap_node);

        for(;;){
            heap_peek(heap,&heap_node);
            if(heap_node.index > i-k){
                break;
            }
            heap_pop(heap);
        }
        returnNums[returnLen++] = heap_node.val;
    }

    heap_free(heap);
    
    *returnSize = returnLen;
    return returnNums;
}

猜你喜欢

转载自blog.csdn.net/ZRXSLYG/article/details/112254290