一刷 05/2022
Time O(logk) -> k is the index of the target number
Space O(1)
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* public int get(int index) {}
* }
*/
class Solution {
public int search(ArrayReader reader, int target) {
// Find a upper bound of the range in which we can search for the target
int end = 1;
while (reader.get(end) < target) {
end = end << 1;
}
int start = end >> 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (reader.get(mid) == target) {
return mid;
}
if (reader.get(mid) < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
}
No comments:
Post a Comment