【Leetcode】H-Index II
2016-06-03 22:25
330 查看
题目链接:https://leetcode.com/problems/h-index-ii/
题目:
Follow up for H-Index: What if the
is sorted in ascending order? Could you optimize your algorithm?
Hint:
Expected runtime complexity is in O(log n) and the input is sorted.
思路:
用二分查找法。
算法:
[java] view
plain copy
public int hIndex(int[] citations) {
int h = 0;
int right = citations.length - 1, left = 0, mid = (right - left) / 2 + left;
while (right >= left) {
if (citations[mid] < citations.length - mid) {
left = mid + 1;
} else if (citations[mid] >= citations.length - mid) {
right = mid - 1;
h = citations.length - mid;
if (mid - 1 >= 0 && citations[mid - 1] < citations.length - mid + 1)
return h;
}
mid = (right - left) / 2 + left;
}
return h;
}
题目:
Follow up for H-Index: What if the
citationsarray
is sorted in ascending order? Could you optimize your algorithm?
Hint:
Expected runtime complexity is in O(log n) and the input is sorted.
思路:
用二分查找法。
算法:
[java] view
plain copy
public int hIndex(int[] citations) {
int h = 0;
int right = citations.length - 1, left = 0, mid = (right - left) / 2 + left;
while (right >= left) {
if (citations[mid] < citations.length - mid) {
left = mid + 1;
} else if (citations[mid] >= citations.length - mid) {
right = mid - 1;
h = citations.length - mid;
if (mid - 1 >= 0 && citations[mid - 1] < citations.length - mid + 1)
return h;
}
mid = (right - left) / 2 + left;
}
return h;
}
相关文章推荐
- datalist 绑定数据为空时,显示提示信息
- 204. Count Primes
- 【Leetcode】Integer to Roman
- main方法写错导致的一个错误
- 张宴博客------F 5 详解
- iOS学习总结
- 动态分配内存与静态内存
- 【Leetcode】Reverse Bits
- SICP 习题1. 29 simpson 积分
- python 内置函数和函数装饰器
- Windbg(2)
- springMVC+mybatis+ehcache详细配置
- MLlib数据类型
- IOS动画简介
- 通用单例模式
- ES 父子文档查询
- 腾讯新版MSDK for Unity
- 从多个表中检索记录
- 学术诚信与职业道德 感受
- 关于提高webview里下载apk安装包成功率的研究