IncredibleThings

导航

LeetCode-H-Index II

Given an array of citations sorted in ascending order (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."

Example:

Input: citations = [0,1,3,5,6]
Output: 3 
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had 
             received 0, 1, 3, 5, 6 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, her h-index is 3.
Note:

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

Follow up:

This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?

对于一个有序的序列,我们自然想到的就是二分查找算法。如何来做呢?我们画图分析一下:

1. 上图是一个递增的序列,下面一行是此处若满足条件对应的h值。可见h值是降序序列。因此在二分查找的过程中,如果某个h值满足条件(即h值小于它对应的值),我们就到前半部分继续查找;如果h值不满足条件(即h值大于它对应的值),我们就到前半部分继续查找。

2. 对于一些边界情况,如果在最左边查找成功或者失败,则此时left=0,h=len(即len-left);如果在最右边查找失败,left会溢出,left=len,此时h=len-left=0.

 

class Solution {
    public int hIndex(int[] citations) {
        int len = citations.length;
        int low = 0;
        int high = citations.length-1;
        while (low <= high){
            int mid = low+(high-low)/2;
            if(citations[mid] >= len-mid) high = mid - 1;
            else low = mid + 1;
        }
        return len - low;
    }
}

 

posted on 2018-07-17 10:49  IncredibleThings  阅读(111)  评论(0编辑  收藏  举报