Leetcode Note: H-Index II
I. Description
Follow up for H-Index: What if the citations array is sorted in ascending order? Cocould you optimize your algorithm?
Ii. Question Analysis
This question is basically the same as the requirements of the H-Index question. It only provides one more condition, that is, the input array itself is in ascending order, so the operation is actually much more convenient, no need to use secondary arrays. You can still use the H-Index method to traverse the array from the back to the front to calculate the h Index. The algorithm complexity isO(n)
But the faster method is to use binary search, reducing complexityO(logn)
.
Iii. Sample Code
// Simply traverse the array from the back to the front, which is time consuming class Solution {public: int hIndex (vector
& Citations) {if (citations. size () = 0) return 0; int result = 0; for (int I = citations. size ()-1; I> = 0; -- I) {if (result> = citations [I]) return result; ++ result;} return citations. size ();}};
// Binary search, faster class Solution {public: int hIndex (vector
& Citations) {int size = citations. size (); if (size = 0) return 0; int left = 0, right = size-1; while (left <right) {int mid = left + (right-left)/2; if (size-mid> citations [mid]) left = mid + 1; else right = mid ;} return (size-right) <citations [right]? (Size-right): citations [right] ;}};
Iv. Summary
The question prompt is slightly redundant.