leetcode-剑指59-I-OK
同主站239,但是239用这段代码会超时,需要优化
address
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize){
if(numsSize==0){
returnSize[0] =0;
return NULL;
}
int i,j; // 循环用的
returnSize[0] = numsSize-k+1; // 返回大小
int* answer = (int*)malloc(sizeof(int)*(numsSize-k+1)); // 需要返回的数
int count = returnSize[0];
bool ok[numsSize-k+1];
for(i = 0; i < count;i++)
ok[i] = false;
int order[numsSize+1];
int mid[numsSize+1];
for(i = 0;i<numsSize;i++){
mid[i+1] = nums[i];
order[i+1] = i;
}
// 堆调整以及建堆的函数
void head_adjust(int arr[], int k, int size_adjust){
arr[0] = arr[k];
order[0] =order[k];
int i;
for (i=2*k ; i <= size_adjust ; i*=2){
if (i+1<= size_adjust && arr[i] <arr[i+1])
i +=1;
if (arr[0]>= arr[i])
break;
else{
arr[k] = arr[i];
order[k] = order[i];
k = i;
}
}
arr[k] = arr[0];
order[k] = order[0];
}
void build_max_heap(int *arr, int size){
for (int i= size/2; i>0; i--){
head_adjust(arr, i, size);
}
}
// 装入函数
void fill(int position,int big){
answer[position] = big;
ok[position] = true;
count--;
}
bool checkfull(){
if(count==0)
return true;
return false;
}
// 检查 是否在0 ~ numsSize-k中
bool check(int a){
if((a>=0)&&(a<=numsSize-k)&&(!ok[a]))
return true;
return false;
}
void doAbigONE(){
for(int m = order[1]+1-k; m<=order[1]; m++){
if(check(m)){
fill(m,mid[1]);
if(checkfull())
return;
}
}
}
// 每次对大根堆的根进行处理,然后把尾 换到根来,调整根,循环往复,直到滑动窗口被填完
build_max_heap(mid,numsSize);
doAbigONE();
for(i = numsSize; i>1; i--){
if(checkfull())
break;
mid[1] = mid[i];
order[1] = order[i];
head_adjust(mid,1,i-1);
doAbigONE();
}
return answer;
}