Search in a big sorted array,這個比以前的二分法模板多了一個很不一樣的特性,就是沒法知道一個重要的條件end值,也是題目中強調的重點 The array is so big so that you can not get the length of the whole array directly~因此這裏單獨分析這個問題~python
通常涉及到sorted array,確定能夠的解決方法是for loop,然而for loop的複雜度是O(n),並且對於這個長度沒法衡量的big sorted array也並不適用。並且,看到sorted array能夠聯想到的就是binary search啦~因此第一步就是怎麼肯定這個end值~less
index = 1 while reader.get(index) < target: index = index * 2 start = 0 end = index
(這個reader是題目給定的python get element的方法)因爲是sorted array,若是這個 target 存在,那麼必然從某個節點開始,以後全部的元素都大於這個 target,咱們保留有解的一半的思想,這裏至關於就給這個big sorted array分爲了兩個部分,咱們取有解的前一部分,放棄必然大於target的後一部分。這時候也就找到了end的值~就把他轉化成了一個長度可計的sorted array,再套用二分法的解題模板就能夠解決這個問題。po個解法~oop
""" 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) < target: index = index * 2 start = 0 end = index while start + 1 < end: mid = start + (end - start) / 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