• 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.

    复杂度

    时间 O(logN) 空间 O(1)

    思路

    在升序的引用数数组中,假设数组长为N,下标为i,则N - i就是引用次数大于等于下标为i的文献所对应的引用次数的文章数。如果该位置的引用数小于文章数,则说明则是有效的H指数,如果一个数是H指数,那最大的H指数一定在它的后面(因为是升序的)。根据这点就可已进行二分搜索了。这里min = mid + 1的条件是citations[mid] < n - mid,确保退出循环时min肯定是指向一个有效的H指数。

    只有一个H指数,就是相等时候书本数目,所以等于就直接return.

    本题不同于H-Index I在于,那道题是以citation数来标志H index。因为在那道题中,citation数是连续的,我们这道题,书本数是连续的,所以要以相遇时候右边书本数来标志H-index

    By definition, if h of his/her N papers have at least h citations each, then h is the H-index
    所以这道题我们就是找citation[k] >= # of books的左边沿,sorted array左边都是citation[k]<#of books, 右边都是citation[k]>=#of books, 左指针和右指针相遇以后左指针l处就是左边沿,len-l就是所求H-index

    以[0,1,2,5,6] ,相遇时, l 在5,len-l就是H-index

    总结:这两道题,看H-index定义很重要,第一题,citation[k]连续,应以citation数目标示H-index, H-index找寻方法应该是:index k is his h-index if the summation of all elements fromcounts[k] to counts[L] is no less than k.  

    第二题,#of books连续,应以# of books标示H-index,找寻方法应该是: find h of books that have at least h citations each

     1 public class Solution {
     2     public int hIndex(int[] citations) {
     3         if (citations==null || citations.length==0) return 0;
     4         int len = citations.length;
     5         int l=0, r=len-1;
     6         while (l <= r) {
     7             int m = (l+r)/2;
     8             if (citations[m] == len-m) return len-m;
     9             else if (citations[m] < len-m) {
    10                 l = m+1;
    11             }
    12             else r = m-1;
    13         }
    14         return len-l;
    15     }
    16 }

    也可以 return len-r-1, 也是对的。因为相遇的时候r刚好在实际指示H-index的数组元素的左侧

  • 相关阅读:
    是否可能两个ETH私钥对应同一个地址
    使用 neon-wallet-db + neon-js + NEO-cli /rpc 搭建轻钱包服务端
    从源码看 angular/material2 中 dialog模块 的实现
    个人从源码理解JIT模式下angular编译AppModule的过程
    个人从源码理解angular项目在JIT模式下的启动过程
    使用angular的HttpClient搭配rxjs
    把angular项目整合到.net mvc中
    小程序开发整理
    ABC: Always Be Coding
    postgresql的psql常用命令-4
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5074806.html
Copyright © 2020-2023  润新知