题目大意:给你已排序的引用次数的数组,求h-index。
Problem:
https://leetcode.com/problems/h-index-ii/description/
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
Solution 1: Linear Scan
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua // Running time: 33 ms class Solution { public: int hIndex(vector<int>& citations) { for (int i = 1; i <= citations.size(); ++i) if (*(citations.rbegin() + i - 1) < i) return i - 1; return citations.size(); } }; |
Solution 2: Binary Search
Time Complexity: O(logn)
Space Complexity: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Running time: 9 ms class Solution { public: int hIndex(vector<int>& citations) { int n = citations.size(); int l = 0; int r = n; while (l < r) { int m = l + (r - l) / 2; if (citations[n - m - 1] <= m) r = m; else l = m + 1; } return l; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment