给定大小为N的数组。数组被分为大小为k的子数组。找到每个子数组的最大值。
子数组为滑动窗口。
子数组为1 2. 2 3. 3 4. 4 5. 5 6.
An array of size N is given. Array is sub divided into sub array of size K. Find maximum value of each sub array.
It is sliding window.
Let array be
1 2 3 4 5 6
k=2
Sub array 1 2. 2 3. 3 4. 4 5. 5 6.
下面使用基于双链表的双端队列,队列未实现从队首插入数据。
由maxSlidingWindow来实现整个查找最大值的过程。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//queue中的节点
struct DQnode
{
int data , index;//数据 和 下标
struct DQnode* next,*prev;
};
struct DQueue//queue有头和尾指针
{
struct DQnode*front,*rear;
};
struct DQueue* createDQueue()//创建队列
{
struct DQueue*newNode = (struct DQueue*)malloc(sizeof(struct DQueue));
newNode->front = newNode->rear = NULL;
return newNode;
}
struct DQnode*newDQnode(int data,int index)//根据数据和下标创建节点
{
struct DQnode*temp = (struct DQnode*)malloc(sizeof(struct DQnode));
temp->index = index;
temp->data = data;
temp->prev = temp->next = NULL;
return temp;
}
int isDQueueEmpty(struct DQueue*DQ)//判断队列是否为空
{
return (DQ->front==NULL);
}
void DQPushBack(struct DQueue* DQ,int data ,int index)//往队列尾部放入数据
{
struct DQnode* temp = newDQnode(data,index);
if (DQ->front == NULL&&DQ->rear == NULL)
{
DQ->front = DQ->rear = temp;
}
else
{
DQ->rear->next = temp;
temp->prev = DQ->rear;
DQ->rear = temp;
}
}
void DQPopFront(struct DQueue* DQ)//从队列头部弹出数据
{
if (isDQueueEmpty(DQ))
{
return ;
}
struct DQnode*temp = DQ->front;
if (DQ->front == DQ->rear)
{
DQ->front = DQ->rear = NULL;
}
else
{
DQ->front->next->prev = NULL;
DQ->front = DQ->front->next;
temp->next = NULL;
}
free(temp);
temp = NULL;
}
void DQPopBack(struct DQueue* DQ)//从队列尾部弹出数据
{
if (isDQueueEmpty(DQ))
{
return ;
}
struct DQnode *temp = DQ->rear;
if (DQ->rear == DQ->front)
{
DQ->front = DQ->rear = NULL;
}
else
{
DQ->rear->prev->next = NULL;
DQ->rear = DQ->rear->prev;
temp->prev = NULL;
}
free(temp);
temp = NULL;
}
struct DQnode* frontDQueue(struct DQueue *DQ)//取得头结点
{
if (isDQueueEmpty(DQ))
{
return NULL;
}
return DQ->front;
}
struct DQnode* backDQueue(struct DQueue*DQ)//取得尾节点
{
if (isDQueueEmpty(DQ))
{
return NULL;
}
return DQ->rear;
}
void maxSlidingWindow(int arr[],int n,int k)
{
int i;
struct DQueue* DQ = createDQueue();
for (i = 0;i<k;i++)
{
while (!isDQueueEmpty(DQ)&&arr[i]>=backDQueue(DQ)->data)
DQPopBack(DQ);//弹出比arr[i]小的值
DQPushBack(DQ,arr[i],i);
}//保证队首有最大值 并且队列的值从队首到队尾是从大到小
for (;i<n;i++)
{
printf("%d ",arr[frontDQueue(DQ)->index]);//第一次输出 , 输出队首的最大值 总共输出n-k次 但是总共应输出n-k+1次
while (!isDQueueEmpty(DQ)&&(frontDQueue(DQ)->index<=i-k))//从队首弹出下标小于等于 i-k 的数据
{
DQPopFront(DQ);
}
while (!isDQueueEmpty(DQ)&&(arr[i]>=backDQueue(DQ)->data))
{
DQPopBack(DQ);//弹出比arr[i]小的数据
}
DQPushBack(DQ,arr[i],i);
}
printf("%d ",arr[frontDQueue(DQ)->index]);//第n-k+1次输出
}
int main()
{
int arr[] = {5,6,1,2,3,4,5,6,7,8,9};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
maxSlidingWindow(arr,n,k);
scanf("%d");
return 0;
}