Find an element in an infinite length sorted array

后端 未结 7 1144
北海茫月
北海茫月 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:30

    You can apply binary search more or less directly with a small modification. This will roughly correspond to your Approach 2.

    Basically, pick some number B and set A to 0, then check if the element you're looking for is between A and B. If it is, perform the usual kind of binary search in these boundaries, otherwise set B=A and A=2*A and repeat. This will take O(log(M)), where M is the position of the element you're looking for in the array.

提交回复
热议问题