702. Search in a Sorted Array of Unknown Size
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
/**
* // 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 low = 0, high = Integer.MAX_VALUE;
while(low <= high) {
int mid = low + (high-low)/2;
int val = reader.get(mid);
if(val == target) {
return mid;
} else if(val < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}/**
* Time complexity :
* Space complexity :
*/
/**
* // 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 high = 1;
while(reader.get(high) < target) {
high *= 2;
}
int low = high / 2;
while(low <= high) {
int mid = low + (high-low)/2;
int val = reader.get(mid);
if(val == target) {
return mid;
} else if(val < target) {
low = mid+1;
} else {
high = mid-1;
}
}
return -1;
}
}