274. H 指数 H-Index

题目 <https://leetcode-cn.com/problems/h-index/>

用堆,堆的大小就是H指数

当论文引用次数大于堆大小时,入堆;然后删除堆中,论文引用次数小于堆大小的

void push(int *heap,int *heapSize,int val){
    int tail = (*heapSize)++;
    int head;

    for(;tail!=0;){
        head = (tail-1)/2;
        if(heap[head] > val){
            heap[tail] = heap[head];
            tail = head;
        }else{
            break;
        }
    }
    heap[tail] = val;
}

void pop(int *heap,int *heapSize){
    //if(*heapSize == 0){
    //    return;
    //}
    int head,tail,val;
    heap[0] = heap[--(*heapSize)];

    val = heap[0];
    head = 0;
    tail = 2*head+1;
    while(tail<*heapSize){
        if(tail+1<*heapSize&&heap[tail+1]<heap[tail]){
            tail++;
        }
        if(val>heap[tail]){
            heap[head] = heap[tail];
            head = tail;
            tail = 2*head+1;
        }else{
            break;
        }
    }
    heap[head] = val;
}


int hIndex(int* citations, int citationsSize){
    int *heap = malloc(sizeof(int)*citationsSize);
    int heapSize=0;

    int i;
    for(i=0;i<citationsSize;i++){
        if(citations[i] > heapSize){
            push(heap,&heapSize,citations[i]);
            while(heap[0]<heapSize){
                pop(heap,&heapSize);
            }
        }
    }
    free(heap);
    return heapSize;
}

猜你喜欢

转载自blog.csdn.net/ZRXSLYG/article/details/111936246