首页 > 其他 > 详细

leetcode笔记:H-Index II

时间:2016-02-01 19:00:25      阅读:99      评论:0      收藏:0      [点我收藏+]

一. 题目描述

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

二. 题目分析

该题与H-Index一题的要求基本一致,只是多提供了一个条件,即传入的数组本身已经是升序排列的,因此实际上操作会方便许多,也无需再使用辅助数组。该题仍然可以使用H-Index方法从后往前遍历数组,即可计算出h指数,算法复杂度为O(n),但更快的方法是使用二分查找,复杂度降为O(logn)

三. 示例代码

// 简单的从后往前遍历数组,较为耗时
class Solution {
public:
    int hIndex(vector<int>& citations) {
        if (citations.size() == 0) return 0;
        int result = 0;
        for (int i = citations.size() - 1; i >= 0; --i)
        {
            if (result >= citations[i])
                return result;
            ++result;
        }
        return citations.size();
    }
};
// 二分查找,效率更快
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int size = citations.size();
        if (size == 0)
            return 0;
        int left = 0, right = size - 1;
        while (left < right){
            int mid = left + (right - left) / 2;
            if (size - mid > citations[mid])
                left = mid + 1;
            else
                right = mid;
        }
        return (size - right) < citations[right] ? (size - right) : citations[right];
    }
};

四. 小结

题目的提示略显多余。

leetcode笔记:H-Index II

原文:http://blog.csdn.net/liyuefeilong/article/details/50619168

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!