LeetCode 275. H-Index II(文献)

来源:互联网 发布:布袋寅泰 知乎 编辑:程序博客网 时间:2024/05/21 11:07

原题网址:https://leetcode.com/problems/h-index-ii/

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.

方法一:从大到小扫描,时间复杂度O(n)

public class Solution {    public int hIndex(int[] citations) {        int h=0;        for(int i=citations.length-1; i>=0 && citations[i]>h; i--,h++);        return h;    }}
方法二:二分法查找,时间复杂度O(logn)

public class Solution {    public int hIndex(int[] citations) {        int i=0, j=citations.length-1;        while (i<=j) {            int m = (i+j) >> 1;            if (citations[m] == citations.length-m) return citations.length-m;            if (citations[m] > citations.length-m) j=m-1; else i=m+1;        }        return citations.length-i;    }}

另一种实现:

public class Solution {    public int hIndex(int[] citations) {        int i=0, j=citations.length-1;        while (i<=j) {            int m=(i+j)/2;            if (citations[m]>=citations.length-m) j=m-1; else i=m+1;        }        return citations.length-i;    }}


0 0
原创粉丝点击