运行环境:VS2019(C语言编写)
程序目的:实现力扣滑动窗口问题
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
------------------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof
代码问题:缓冲区溢出错误 C6386
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define MAXSIZE 100
typedef struct Queue {
int front;
int rear;
int* base;
}Squeue;
Squeue* InitQueue() {
Squeue* q = (Squeue*)malloc(sizeof(Squeue));
if (q == NULL) return NULL;
q->base = (int*)malloc(sizeof(int) * MAXSIZE);
q->front = q->rear = -1;
return q;
}
void Enqueue(Squeue* q, int Elem) {
if (q->rear == MAXSIZE) return;
(*q).base[++((*q).rear)] = Elem;
return;
}
int Dequeue(Squeue* q) {
if ((*q).rear == (*q).front) return -10;
int val = (*q).base[++((*q).front)];
return val;
}
int Bigest(Squeue* q) {
int bigest = -100;
while ((*q).front != (*q).rear) {
int p = Dequeue(q);
if (p > bigest) {
bigest = p;
}
}
return bigest;
}
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) {
if (nums == NULL) return NULL;
int* Bnums = (int*)malloc(sizeof(int) * numsSize);
if (Bnums == NULL) return NULL;
memset(Bnums, -100, sizeof(int) * numsSize);
if (numsSize <= k) {
int i = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] > Bnums[0]) {
Bnums[0] = nums[i];
}
}
*returnSize = 1;
return Bnums;
}
Squeue* q = InitQueue();
int as = 0;
for (int i = 0; i < numsSize; i++) {
int j = i;
while (j < k) {
Enqueue(q, nums[j]);
}
/**
这里写入数据会报C6386
缓冲区溢出的错误
**/
Bnums[as] = Bigest(q);
k++;
as++;
}
free(q->base);
q->base = NULL;
free(q);
q = NULL;
*returnSize = as;
return Bnums;
}
int main() {
int L;
printf("输入需要创建的数组长度L:\n");
scanf_s("%d", &L);
int* nums = (int*)malloc(sizeof(int) * L);
if (nums == NULL) return -1;
int flag;
int i = 0;
int* Nums = nums;
printf("输入%d个数字:\n", L);
for (int i = 0; i < L; i++) {
scanf_s("%d", &flag);
*nums++ = flag;
}
int res = 0;
int k;
printf("输入滑动窗口的大小:\n");
scanf_s("%d", &k);
int* result = maxSlidingWindow(Nums, L, k, &res);
for (int i = 0; i < res; i++) {
printf("%d\n", result[i]);
}
return 0;
}