Let's make this one less mysterious. For 275. H-Index II, the solution in this repository is mainly a two pointers solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: two pointers.
The notes already sitting in the source point us in the right direction:
- binary search
- https://leetcode.com/problems/h-index-ii/discuss/71063/Standard-binary-search
- time: O(logN), space: O(1)
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are hIndex.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(logN), space: O(1)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//binary search
02//https://leetcode.com/problems/h-index-ii/discuss/71063/Standard-binary-search
03//Runtime: 32 ms, faster than 88.51% of C++ online submissions for H-Index II.
04//Memory Usage: 18.7 MB, less than 47.45% of C++ online submissions for H-Index II.
05//time: O(logN), space: O(1)
06class Solution {
07public:
08 int hIndex(vector<int>& citations) {
09 int n = citations.size();
10 int l = 0, r = n-1;
11 int mid;
12
13 /*
14 c: 3, 3, 5, 8, 25
15 index0: 0, 1, 2, 3, 4 (original index)
16 index1: 5, 4, 3, 2, 1 (how many papers having citation >= c[index0])
17
18 we want to find the first(largest) index1 s.t.
19 c[index0] >= index1,
20 i.e. to find the first(smallest) index0 s.t.
21 c[index0] >= n-index0
22 */
23 while(l <= r){
24 mid = l + (r-l)/2;
25 //convert from index0 to index1, serves as 'h'
26 int count = n-mid;
27 if(citations[mid] == count){
28 return count;
29 }else if(citations[mid] > count){
30 //r will be an invalid value
31 r = mid-1;
32 }else if(citations[mid] < count){
33 l = mid+1;
34 }
35 }
36
37 //r+1: convert it to a valid value
38 /*
39 n-(r+1): convert from index0 to index1,
40 i.e. get its count
41 */
42
43 return n - (r+1);
44 }
45};
Cost