您的位置:首页 > 其它

LeetCode 275. H-Index II(文献)

2016-04-13 12:14 465 查看
原题网址: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:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: