1050. Unknown-Length Shelf
A shelf holds a row of numbered crates sorted in ascending order with no repeats, but nobody knows how many crates it carries. You get an ArrayReader called reader. The call reader.get(i) returns the number on crate i (0-indexed), or 2147483647 when position i is beyond the last crate.
Return the index of the crate whose number equals target, or -1 if there is no such crate. All real crate numbers are smaller than 2147483647. You may call reader.get at most 64 times, so look for an approach that needs O(log n) calls.
Example 1
- Input:
- reader = [-3,2,6,11,40], target = 11
- Output:
- 3
- Explanation:
Crate 3 carries the number 11, which the search finds after probing outward and then halving the range.
Example 2
- Input:
- reader = [4,9,15], target = 10
- Output:
- -1
- Explanation:
No crate holds 10, so after narrowing the range the search ends and returns -1.
Constraints
1 ≤ shelf length ≤ 2000
-109 ≤ crate number, target ≤ 109
Crate numbers are strictly increasing
At most 64 calls to reader.get
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Calls
- You may call
ArrayReader.get(index)at most 64 times per case. It is provided; you do not write it.
Expected complexity
- Time
- O(log n) calls
- Space
- O(1)