Skip to content

Commit

Permalink
correct the algorithm from O(n) to O(log(n))
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Nov 8, 2015
1 parent d173f1e commit c022965
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 37 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ LeetCode
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./algorithms/cpp/moveZeroes/moveZeroes.cpp)|Easy|
|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | [C++](./algorithms/cpp/perfectSquares/PerfectSquares.cpp)|Medium|
|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|
|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [C++](./algorithms/cpp/h-Index/h-Index_II.cpp)|Medium|
|275|[H-Index II](https://leetcode.com/problems/h-index-ii/)| [C++](./algorithms/cpp/h-Index/h-Index.II.cpp)|Medium|
|274|[H-Index](https://leetcode.com/problems/h-index/)| [C++](./algorithms/cpp/h-Index/h-Index.cpp)|Medium|
|273|[Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)| [C++](./algorithms/cpp/integerToEnglishWords/IntegerToEnglishWords.cpp)|Medium|
|268|[Missing Number](https://leetcode.com/problems/missing-number/)| [C++](./algorithms/cpp/missingNumber/MissingNumber.cpp)|Medium|
Expand Down
33 changes: 33 additions & 0 deletions algorithms/cpp/h-Index/h-Index.II.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Source : https://leetcode.com/problems/h-index-ii/
// Author : Hao Chen
// Date : 2015-11-08

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



class Solution {
public:
// binary search - O(log(n))
int hIndex(vector<int>& citations) {
int n = citations.size();
int low = 0, high = n-1;

while( low <= high ) {
int mid = low + (high-low)/2;
if (citations[mid] == n - mid) {
return n - mid;
}else if (citations[mid] > n-mid){
high = mid - 1;
}else {
low = mid + 1;
}
}
return n-low;
}
};
36 changes: 0 additions & 36 deletions algorithms/cpp/h-Index/h-Index_II.cpp

This file was deleted.

0 comments on commit c022965

Please sign in to comment.