首页 > 其他 > 详细

[LeetCode] H-Index II

时间:2015-11-07 14:49:40      阅读:280      评论: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.

解题思路

二分法。

实现代码

C++:

// Runtime: 12 ms
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int len = citations.size();
        int left = 0;
        int right = len - 1;
        while (left <= right)
        {
            int mid = left + (right - left) / 2;
            if (citations[mid] >= len - mid)
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }

        return len -left;
    }
};

Java:

// Runtime: 12 ms
public class Solution {
    public int hIndex(int[] citations) {
        int len = citations.length;
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (citations[mid] >= len - mid) {
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
        }

        return len - left;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] H-Index II

原文:http://blog.csdn.net/foreverling/article/details/49701415

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