275. H-Index II
来源:互联网 发布:higo出租软件 编辑:程序博客网 时间:2024/05/01 12:33
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.
排序了,可以用二分查找了。
二分查找的时候由于不是找某个特定的元素,而是找一个【尽量靠左】的index使得citations[index]>=len-index,所以进入左子区间前先检查一下,以免漏掉要查找的位置。
例如[1,2,5,6,8],第一次搜索mid=2,如果进入左区间,左区间里没有index满足条件,将错过要查找的位置。
又例如[1,4,5,6,8],第一次搜索mid=2,应该进入左区间,因为index=1,满足条件。
为了区分以上两种情况,进入左区间前做检查,看看当mid-1>=lo时是否满足
citations[mid-1]>=len-mid+1
满足就可以继续进入左区间查找。
public int hIndex(int[] citations){int len=citations.length;if(len<1)return 0;int index=find(citations, 0, len-1);if(citations[index]<len-index)return 0;return len-index;}public int find(int[] citations,int lo,int hi){if(lo==hi)return lo;int mid=(lo+hi)>>1;if(citations[mid]>=citations.length-mid){if(mid-1>=lo&&(citations[mid-1]>=citations.length-mid+1))return find(citations, lo, mid-1);return mid;}return find(citations, mid+1,hi);}
0 0
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 275. H-Index II
- 274. H-Index & 275. H-Index II
- [leetcode] 275.H-Index II
- 275. H-Index II LeetCode
- Origin
- (OK)(OK) QEMU-KVM —— HOST AND GUEST can ping each other
- 【项目管理和构建】十分钟教程,eclipse配置maven + 创建maven项目(二)
- 第十一天:制定进度计划、错题整理、进度压缩、资源平衡和资源平滑、关键路径和关键链对比
- 205. Isomorphic Strings
- 275. H-Index II
- 人的潜力和极限
- Python中maxint与系统位数(32/64)的关系
- nginx ssl配置
- 使用ImageNet在faster-rcnn上训练自己的分类网络
- 条件编译
- Codeforces 358 . B Alyona and Mex
- C#基础(2)
- Linux内核驱动之DDR3(一)寻址