comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
中等 |
|
这是一个交互问题。
您有一个升序整数数组,其长度未知。您没有访问数组的权限,但是可以使用 ArrayReader
接口访问它。你可以调用 ArrayReader.get(i)
:
-
返回数组第
ith
个索引(0-indexed)处的值(即secret[i]
),或者 -
如果
i
超出了数组的边界,则返回231 - 1
你也会得到一个整数 target
。
如果存在secret[k] == target
,请返回索引 k
的值;否则返回 -1
你必须写一个时间复杂度为 O(log n)
的算法。
示例 1:
输入:secret
= [-1,0,3,5,9,12],target
= 9 输出: 4 解释: 9 存在在 nums 中,下标为 4
示例 2:
输入:secret
= [-1,0,3,5,9,12],target
= 2 输出: -1 解释: 2 不在数组中所以返回 -1
提示:
1 <= secret.length <= 104
-104 <= secret[i], target <= 104
secret
严格递增
我们先定义一个指针
接下来,我们定义一个指针
时间复杂度
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader: "ArrayReader", target: int) -> int:
r = 1
while reader.get(r) < target:
r <<= 1
l = r >> 1
while l < r:
mid = (l + r) >> 1
if reader.get(mid) >= target:
r = mid
else:
l = mid + 1
return l if reader.get(l) == target else -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) {
int r = 1;
while (reader.get(r) < target) {
r <<= 1;
}
int l = r >> 1;
while (l < r) {
int mid = (l + r) >> 1;
if (reader.get(mid) >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return reader.get(l) == target ? l : -1;
}
}
/**
* // 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 r = 1;
while (reader.get(r) < target) {
r <<= 1;
}
int l = r >> 1;
while (l < r) {
int mid = (l + r) >> 1;
if (reader.get(mid) >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return reader.get(l) == target ? l : -1;
}
};
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* type ArrayReader struct {
* }
*
* func (this *ArrayReader) get(index int) int {}
*/
func search(reader ArrayReader, target int) int {
r := 1
for reader.get(r) < target {
r <<= 1
}
l := r >> 1
for l < r {
mid := (l + r) >> 1
if reader.get(mid) >= target {
r = mid
} else {
l = mid + 1
}
}
if reader.get(l) == target {
return l
}
return -1
}
/**
* class ArrayReader {
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* get(index: number): number {};
* };
*/
function search(reader: ArrayReader, target: number): number {
let r = 1;
while (reader.get(r) < target) {
r <<= 1;
}
let l = r >> 1;
while (l < r) {
const mid = (l + r) >> 1;
if (reader.get(mid) >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return reader.get(l) === target ? l : -1;
}