Find a number in sorted multidimentional array with binary search

后端 未结 10 907
深忆病人
深忆病人 2021-01-14 02:12

we got an increasing sorted multidimensional array for example:

int[][] mat = {{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};

How can

10条回答
  •  鱼传尺愫
    2021-01-14 02:41

    There are different ways to define 'order' in a two-dimensional array. For the order in your example, do bin search on the first element of each row, to find the row, and then do bin search again inside the row. if the number of rows is >= than the number of columns, you can optimize doing binary search on the elements of the diagonal that starts at (0,0), then do another binary search on the rest of the row.

提交回复
热议问题