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;
}
-
单调队列
-
调试框架
#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;
}
来源:CSDN
作者:向日葵10086
链接:https://blog.csdn.net/sunflower_boy/article/details/104116415