Search in a big sorted array, this is more than the previous dichotomy template a very different feature, is unable to know an important condition end value, is also the focus of emphasis in the topic of the array is so big so it can not GE t the length of the whole array directly~ so here alone to analyze the problem ~
The sorted array is generally involved, and the solution that is definitely possible is for loop, but the complexity of the For loop is O (n), and it does not apply to big sorted arrays that cannot be measured in length. Also, see the sorted array can be linked to think of binary search ~ So the first step is how to determine the end value ~
index = 1 while reader.get (index) < target: index = index * 2 start = 0 end = Index
(This reader is the method of the topic given by the python get element) because it is a sorted array, if this target exists, then it must start from a certain node, then all elements are larger than this target, and we reserve half the thought of the solution, This is equivalent to the big sorted array is divided into two parts, we take the first part of the solution, discard must be greater than the latter part of target. At this time also found the value of end ~ turned him into a sorted array of length, and then apply the dichotomy of the solution template can solve the problem. Po a Solution ~
"" "Definition of Arrayreader:class Arrayreader: def get (self, Index): # This would return the number on the given Index # return-1 If index is less than zero. "" Class solution: # @param {Arrayreader} Reader:an instance of Arrayreader # @param {int} target an integer # @ return {int} an integer def searchbigsortedarray (self, Reader, target): index = 1 while reader.get (index) & Lt Target: index = index * 2 start = 0 end = Index while start + 1 < end: mid = start + (end-sta RT)/2 if Reader.get (mid) = = Target: end = mid elif Reader.get (mid) < target: start = Mid
else: end = Mid if Reader.get (start) = = target: return start if reader.get (end) = = target: return End return-1
Two-Part search summary and partial lintcode topic analysis 2