Find an element in an infinite length sorted array

后端 未结 7 1126
北海茫月
北海茫月 2020-12-13 21:51

Given an infinite length sorted array having both positive and negative integers. Find an element in it.

EDIT
All the elements in the array are

7条回答
  •  自闭症患者
    2020-12-13 22:14

    Since the array is infinite, the indexes are necessarily variable-length. That means that doing math on them is not O(1), which in turn means that "binary search with first a search for an endpoint" has a slightly different time complexity than O(log(k)).

    The index math done in the search for the endpoint is just a left shift by one, which takes O(log(k)) because indexes up to k need up to log(k) bits and shifting left by one is linear in the number of bits.

    The index math done in the binary search is all O(log(k)) as well.

    So the actual complexity of both algorithms is O(log(k)^2). The complexity of a linear search would be O(k log k), so it still loses.

提交回复
热议问题