You have a sorted array of unique elements and an unknown size. You do not have an access to the array but you can use the ArrayReader interface to access it. You can call ArrayReader.get(i) that:
returns the value at the ith index (0-indexed) of the secret array (i.e., secret[i]), or
returns 231 - 1 if the i is out of the boundary of the array.
You are also given an integer target.
Return the index k of the hidden array where secret[k] == target or return -1 otherwise.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: secret = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in secret and its index is 4.
Example 2:
Input: secret = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in secret so return -1.
Constraints:
1 <= secret.length <= 104
-104 <= secret[i], target <= 104
secret is sorted in a strictly increasing order.
Solutions
Solution 1
1 2 3 4 5 6 7 8 91011121314151617181920212223
# """# This is ArrayReader's API interface.# You should not implement it, or speculate about its implementation# """# class ArrayReader:# def get(self, index: int) -> int:classSolution:defsearch(self,reader,target):""" :type reader: ArrayReader :type target: int :rtype: int """left,right=0,20000whileleft<right:mid=(left+right)>>1ifreader.get(mid)>=target:right=midelse:left=mid+1returnleftifreader.get(left)==targetelse-1
1 2 3 4 5 6 7 8 910111213141516171819202122
/** * // This is ArrayReader's API interface. * // You should not implement it, or speculate about its implementation * interface ArrayReader { * public int get(int index) {} * } */classSolution{publicintsearch(ArrayReaderreader,inttarget){intleft=0,right=20000;while(left<right){intmid=left+right>>1;if(reader.get(mid)>=target){right=mid;}else{left=mid+1;}}returnreader.get(left)==target?left:-1;}}
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * // This is the ArrayReader's API interface. * // You should not implement it, or speculate about its implementation * class ArrayReader { * public: * int get(int index); * }; */classSolution{public:intsearch(constArrayReader&reader,inttarget){intleft=0,right=20000;while(left<right){intmid=left+right>>1;if(reader.get(mid)>=target){right=mid;}else{left=mid+1;}}returnreader.get(left)==target?left:-1;}};
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * // 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 {} */funcsearch(readerArrayReader,targetint)int{left,right:=0,20000forleft<right{mid:=(left+right)>>1ifreader.get(mid)>=target{right=mid}else{left=mid+1}}ifreader.get(left)==target{returnleft}return-1}