首页 > 代码库 > LeetCode OJ 274. H-Index

LeetCode OJ 274. H-Index

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher‘s h-index.

According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N ? h papers have no more than h citations each."

For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.

Note: If there are several possible values for h, the maximum one is taken as the h-index.

就是一个快排,不过题意有点含糊,至少h citations并不一定意味着一定要有等于h citations的,并且剩下的N - h是no more than,也就是可以存在等于的情况。

void Swap(int A[], int a, int b){
    int tmp = A[a];
    A[a] = A[b];
    A[b] = tmp;
}

int Partition(int* citations, int left, int right){
    int pivot = citations[right];
    int i, j = 0;
    
    for(i = 0; i < right; i++){
        if(citations[i] >= pivot){
            Swap(citations, i, j);
            j++;
        }
    }
    Swap(citations, j, right);
    
    return j;
}

void Quick_Sort(int* citations, int left, int right){
    int pivot_position;
    
    if(left >= right){
        return;
    }
    pivot_position = Partition(citations, left, right);
    Quick_Sort(citations, left, pivot_position - 1);
    Quick_Sort(citations, pivot_position + 1, right);
}

int hIndex(int* citations, int citationsSize) {
    int i;
    
    Quick_Sort(citations, 0, citationsSize - 1);
    for(i = citationsSize - 1; i >= 0 ; i--){
        if(citations[i] >= i + 1){
                return i + 1;
        }
    }
    return 0;
}

 

LeetCode OJ 274. H-Index