Leetcode Note: H-Index II

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.