当前位置: 首页 > 工具软件 > hindex > 使用案例 >

[LeetCode] H-Index II

仉刚洁
2023-12-01

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Hint:

  1. Expected runtime complexity is in O(log n) and the input is sorted.

解题思路

二分法。

实现代码

C++:

// Runtime: 12 ms
class Solution {
public:
    int hIndex(vector<int>& citations) {
        int len = citations.size();
        int left = 0;
        int right = len - 1;
        while (left <= right)
        {
            int mid = left + (right - left) / 2;
            if (citations[mid] >= len - mid)
            {
                right = mid - 1;
            }
            else
            {
                left = mid + 1;
            }
        }

        return len -left;
    }
};

Java:

// Runtime: 12 ms
public class Solution {
    public int hIndex(int[] citations) {
        int len = citations.length;
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (citations[mid] >= len - mid) {
                right = mid - 1;
            }
            else {
                left = mid + 1;
            }
        }

        return len - left;
    }
}
 类似资料: