/**
* // 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) {
}
};
/**
* // 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 {
l,r:=0,10000
for l<=r{
mid:=l+(r-l)/2
if reader.get(mid)==target{
return mid
}else if reader.get(mid)>target{
r = mid-1
}else{
l = mid+1
}
}
return -1
}
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
#class ArrayReader:
# def get(self, index: int) -> int:
ceil = 2**31 - 1
class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
# 按照数组最大的可能性设置左右边界
left = 0
right = 20000
while left < right:
mid = (left + right + 1) >> 1 # 右中位数
if reader.get(mid) == 2147483647: # 如果越界,则右边界收缩
right = mid - 1
elif reader.get(mid) > target: # 如果大于目标值,则右边界收缩
right = mid - 1
else:
left = mid
return left if reader.get(left) == target else -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 index = 0;
while (reader.get(index) != 2147483647) {
if (reader.get(index) == target)
return index;
index ++;
}
return -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 {
private static final int MAX_LENGTH = 20000;
public int search(ArrayReader reader, int target) {
int left = 0;
int right = MAX_LENGTH - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int midValue = reader.get(mid);
if (midValue < target) {
left = mid + 1;
} else if (midValue > target) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
}