Skip to content

Commit c022965

Browse files
committed
correct the algorithm from O(n) to O(log(n))
1 parent d173f1e commit c022965

File tree

3 files changed

+34
-37
lines changed

3 files changed

+34
-37
lines changed

‎README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ LeetCode
1717
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./algorithms/cpp/moveZeroes/moveZeroes.cpp)|Easy|
1818
|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | [C++](./algorithms/cpp/perfectSquares/PerfectSquares.cpp)|Medium|
1919
|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)| [C++](./algorithms/cpp/firstBadVersion/FirstBadVersion.cpp), [Java](./algorithms/java/src/firstBadVersion/firstBadVersion.java)|Easy|
20-
|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [C++](./algorithms/cpp/h-Index/h-Index_II.cpp)|Medium|
20+
|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [C++](./algorithms/cpp/h-Index/h-Index.II.cpp)|Medium|
2121
|274|[H-Index](https://leetcode.com/problems/h-index/)| [C++](./algorithms/cpp/h-Index/h-Index.cpp)|Medium|
2222
|273|[Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)| [C++](./algorithms/cpp/integerToEnglishWords/IntegerToEnglishWords.cpp)|Medium|
2323
|268|[Missing Number](https://leetcode.com/problems/missing-number/)| [C++](./algorithms/cpp/missingNumber/MissingNumber.cpp)|Medium|

‎algorithms/cpp/h-Index/h-Index.II.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Source : https://leetcode.com/problems/h-index-ii/
2+
// Author : Hao Chen
3+
// Date : 2015-11-08
4+
5+
/***************************************************************************************
6+
*
7+
* Follow up for H-Index: What if the citations array is sorted in ascending order?
8+
* Could you optimize your algorithm?
9+
*
10+
***************************************************************************************/
11+
12+
13+
14+
class Solution {
15+
public:
16+
// binary search - O(log(n))
17+
int hIndex(vector<int>& citations) {
18+
int n = citations.size();
19+
int low = 0, high = n-1;
20+
21+
while( low <= high ) {
22+
int mid = low + (high-low)/2;
23+
if (citations[mid] == n - mid) {
24+
return n - mid;
25+
}else if (citations[mid] > n-mid){
26+
high = mid - 1;
27+
}else {
28+
low = mid + 1;
29+
}
30+
}
31+
return n-low;
32+
}
33+
};

‎algorithms/cpp/h-Index/h-Index_II.cpp

-36
This file was deleted.

0 commit comments

Comments
 (0)