[leetcode][Binary Search] H-Index II

来源:互联网 发布:腾讯数据库有多大 编辑:程序博客网 时间:2024/06/07 06:11

题目:

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.
class Solution {public:int hIndex(vector<int>& citations) {if (citations.empty()) return 0;int n = citations.size();int low = 0, high = n - 1;int h = 0;while (high >= low){int mid = low + (high - low) / 2;//找到,直接返回if ((n - mid) == citations[mid]) return n - mid;//更新hint hNew = ((n - mid) < citations[mid])?(n-mid):citations[mid];if (h < hNew) h = hNew;//二分查找if ((n - mid) < citations[mid]) high = mid - 1;else low = mid + 1;}return h;}};


0 0
原创粉丝点击