H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

这道题目是H-Index的follow up。题目的意思让我们在O(log n)的时间复杂度下解决。我们用二分法,这道题目比较trick, 代码如下:
public class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0) return 0;
        int len = citations.length;
        int l = 0;
        int r = len - 1;
        while(l <= r) {
            int m = l + (r - l) / 2;
            if(citations[m] < len - m) {
                l = m + 1;
            } else if(citations[m] > len - m) {
                r = m - 1;
            } else {
                return citations[m];
            }
        }
        return len - r - 1;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2278986
今日推荐