H-Index II

描述

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

分析

设数组长度为n,那么n-i就是引用次数大于等于nums[i]的文章数。如果nums[i]<n-i,说明i是有效的H-Index, 如果一个数是H-Index,那么最大的H-Index一定在它后面(因为是升序的),根据这点就可以进行二分搜索了。

代码

  1. // H-Index II
  2. // Time complexity: O(logn), Space complexity: O(1)
  3. public class Solution {
  4. public int hIndex(int[] citations) {
  5. final int n = citations.length;
  6. int begin = 0;
  7. int end = citations.length;
  8. while (begin < end) {
  9. final int mid = begin + (end - begin) / 2;
  10. if (citations[mid] < n - mid) {
  11. begin = mid + 1;
  12. } else {
  13. end = mid;
  14. }
  15. }
  16. return n - begin;
  17. }
  18. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/search/h-index-ii.html