Last active
June 17, 2019 14:24
-
-
Save yangpeng-chn/5ade8f349c8b31b0646e15d9337a441b to your computer and use it in GitHub Desktop.
Modified Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int findRight(const ArrayReader& reader, int target){ | |
int right = 1; | |
while (reader.get(right) < target) | |
right = right * 2; | |
return right; | |
} | |
int searchInfiniteArray(const ArrayReader& reader, int target) { | |
int left = 0, right = findRight(reader, target); | |
while (left <= right){ | |
int mid = left + (right - left)/2; | |
int val = reader.get(mid); | |
if (val == target) return mid; | |
else if (val < target) | |
left = mid + 1; | |
else right = mid - 1; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment