码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] H-Index II 求H指数之二

时间:2015-09-05 06:38:47      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

 

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

Hint:

  1. Expected runtime complexity is in O(log n) and the input is sorted.

 

这题是之前那道H-Index 求H指数的拓展,输入数组是有序的,让我们在O(log n)的时间内完成计算,看到这个时间复杂度,应该有很敏锐的意识应该用二分查找法,我们最先初始化left和right为0和数组长度len-1,然后取中间值mid,比较citations[mid]和len-mid做比较,如果前者大,则right移到mid之前,反之right移到mid之后,终止条件是left>right,最后返回len-left即可,参见代码如下:

 

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int len = citations.size(), left = 0, right = len - 1;
        while (left <= right) {
            int mid = 0.5 * (left + right);
            if (citations[mid] == len - mid) return mid + 1;
            else if (citations[mid] > len - mid) right = mid - 1;
            else left = mid + 1;
        }
        return len - left;
    }
};

 

LeetCode All in One 题目讲解汇总(持续更新中...)

 

[LeetCode] H-Index II 求H指数之二

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4782695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!