239. 滑动窗口最大值

倖福魔咒の 提交于 2020-01-31 02:31:28

1.暴力法

#define VECTOR_INITIAL_CAPACITY 16
typedef struct {
    int size;
    int capacity;
    int *data;
} Vector;
void init(Vector *vector){
    vector->size = 0;
    vector->capacity = VECTOR_INITIAL_CAPACITY;
    vector->data = malloc(sizeof(int) * vector->capacity);
}
void resize(Vector *vector){
    if(vector->size >= vector->capacity){
        vector->capacity *= 2;
        vector->data = realloc(vector->data, sizeof(int) * vector->capacity);
    }
}
void append(Vector *vector, int value){
    resize(vector);

    vector->data[vector->size++] = value;
}
void free_memory(Vector *vector){
    free(vector->data);
}
bool is_empty(Vector *vector){
    return vector->size == 0;
}
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
    *returnSize = 0;
    if(!numsSize) return NULL;
    if(!k) return NULL;
    Vector tmpRet;
    init(&tmpRet);
    int m;
    for(m=0;(m+k)<=numsSize;m++){
        int maxVal = INT_MIN;
        for(int i=m;i<m+k;i++){
            if(nums[i]>maxVal){
                maxVal = nums[i];
            }
        }
        append(&tmpRet, maxVal);
    }
    *returnSize = m;
    if(!m) return NULL;
    int *ret = (int*)malloc(m*sizeof(int));
    memset(ret, 0, m*sizeof(int));
    memcpy(ret, tmpRet.data, m*sizeof(int));
    return ret;
}

  1. 单调队列

  2. 调试框架

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include <stdbool.h>

int main() {
    int nums[] =  {1,3,-1,-3,5,3,6,7};
    int k = 3;
    int ansSize = 6;
    int ans[] = {3,3,5,5,6,7};
    int retSize = 0;
    int *ret;
    ret = maxSlidingWindow(nums, sizeof(nums)/sizeof(int), k, &retSize);
    if(retSize != ansSize){
        printf("retSize error.retSize:%d, ansSize:%d.", retSize, ansSize);
        return 1;
    }
    for(int i=0;i<retSize;i++){
        if(ans[i] != ret[i]){
            printf("ret error. i:%d, retI:%d, ansI:%d.", i, ret[i], ans[i]);
        }
    }
    printf("Hello, World!\n");
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!