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 }