How do I search for a number in a 2d array sorted left to right and top to bottom?

后端 未结 20 1072
暖寄归人
暖寄归人 2020-11-22 13:03

I was recently given this interview question and I\'m curious what a good solution to it would be.

Say I\'m given a 2d array where all the numbers i

20条回答
  •  醉话见心
    2020-11-22 13:24

    This is a short proof of the lower bound on the problem.

    You cannot do it better than linear time (in terms of array dimensions, not the number of elements). In the array below, each of the elements marked as * can be either 5 or 6 (independently of other ones). So if your target value is 6 (or 5) the algorithm needs to examine all of them.

    1 2 3 4 *
    2 3 4 * 7
    3 4 * 7 8
    4 * 7 8 9
    * 7 8 9 10
    

    Of course this expands to bigger arrays as well. This means that this answer is optimal.

    Update: As pointed out by Jeffrey L Whitledge, it is only optimal as the asymptotic lower bound on running time vs input data size (treated as a single variable). Running time treated as two-variable function on both array dimensions can be improved.

提交回复
热议问题