题目地址:
https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/
给定一个长度未知的有序数组,再给定一个数target,要求返回其在数组中的下标。如果不存在则返回 − 1 -1 −1。
可以使用倍增法先找到target所在的区间,然后用二分法寻找其下标。代码如下:
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* class ArrayReader {
* public:
* int get(int index);
* };
*/
class Solution {
public:
int search(const ArrayReader& reader, int target) {
int l = 0, r = 1;
while (reader.get(r) < target) {
l = r;
r <<= 1;
}
while (l < r) {
int m = l + (r - l + 1 >> 1);
if (reader.get(m) <= target)
l = m;
else
r = m - 1;
}
return reader.get(l) == target ? l : -1;
}
};
时间复杂度 O ( log n ) O(\log n) O(logn),空间 O ( 1 ) O(1) O(1)。