Search in a Sorted Array of Unknown Size
Given an integer array sorted in ascending order, write a function to searchtarget
innums
. Iftarget
exists, then return its index, otherwise return-1
. However, the array size is unknown to you. You may only access the array using anArrayReader
interface, where ArrayReader.get(k)
returns the element of the array at indexk
(0-indexed).
You may assume all integers in the array are less than 10000
, and if you access the array out of bounds,ArrayReader.get
will return2147483647
.
Example 1:
Example 2:
Solution
First find the last valid value (a value which is not 2147483647). Then repeat binary search from 0 to the last found index.
Last updated