接下来,我们定义一个指针 $l = r / 2$,然后我们可以使用二分查找的方法在 $[l, r]$ 的区间内查找目标值的位置。
时间复杂度 $O(\log M)$,其中 $M$ 为目标值的位置。空间复杂度 $O(1)$。
1 2 3 4 5 6 7 8 9101112131415161718192021
# """# 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:"ArrayReader",target:int)->int:r=1whilereader.get(r)<target:r<<=1l=r>>1whilel<r:mid=(l+r)>>1ifreader.get(mid)>=target:r=midelse:l=mid+1returnlifreader.get(l)==targetelse-1
/** * // 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){intr=1;while(reader.get(r)<target){r<<=1;}intl=r>>1;while(l<r){intmid=(l+r)>>1;if(reader.get(mid)>=target){r=mid;}else{l=mid+1;}}returnreader.get(l)==target?l:-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); * }; */classSolution{public:intsearch(constArrayReader&reader,inttarget){intr=1;while(reader.get(r)<target){r<<=1;}intl=r>>1;while(l<r){intmid=(l+r)>>1;if(reader.get(mid)>=target){r=mid;}else{l=mid+1;}}returnreader.get(l)==target?l:-1;}};
/** * // 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{r:=1forreader.get(r)<target{r<<=1}l:=r>>1forl<r{mid:=(l+r)>>1ifreader.get(mid)>=target{r=mid}else{l=mid+1}}ifreader.get(l)==target{returnl}return-1}
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * class ArrayReader { * // This is the ArrayReader's API interface. * // You should not implement it, or speculate about its implementation * get(index: number): number {}; * }; */functionsearch(reader:ArrayReader,target:number):number{letr=1;while(reader.get(r)<target){r<<=1;}letl=r>>1;while(l<r){constmid=(l+r)>>1;if(reader.get(mid)>=target){r=mid;}else{l=mid+1;}}returnreader.get(l)===target?l:-1;}