H-Index II
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
要求用二分法做。
1 public class Solution { 2 public int hIndex(int[] citations) 3 { 4 5 if(citations.length==0)return 0; 6 int left=0; 7 int right=citations.length-1; 8 int mid=0; 9 while(left+1<right) 10 { 11 mid=(left+right)/2; 12 if(citations[mid]<citations.length-mid) 13 { 14 left=mid; 15 } 16 else //citations[mid]>=right-mid 17 { 18 right=mid; 19 } 20 } 21 if(citations[left]>=citations.length-left) return citations.length-left; 22 if(citations[right]>=citations.length-right) return citations.length-right; 23 return 0; 24 } 25 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步