Leetcode H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
Hint:Expected runtime complexity is in O(log n) and the input is sorted.

提示是log(n)的话肯定用二分搜索了:

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int len = citations.size();
        int lo = 0;
        int hi = len;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            int remain = len - mid;
            if (citations[mid] >= remain) {
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        return len - lo;
    }
};
posted @ 2015-09-09 15:55  卖程序的小歪  阅读(100)  评论(0编辑  收藏  举报