Most efficient way to search a sorted matrix?

后端 未结 9 1471
野的像风
野的像风 2020-12-29 14:02

I have an assignment to write an algorithm (not in any particular language, just pseudo-code) that receives a matrix [size: M x N] that is sorted in a way that all of it\'s

9条回答
  •  一整个雨季
    2020-12-29 14:36

    this is wrong answer

    I am really not sure if any of the answers are the optimal answers. I am going at it.

    1. binary search first row, and first column and find out the row and column where "x" could be. you will get 0,j and i,0. x will be on i row or j column if x is not found in this step.
    2. binary search on the row i and the column j you found in step 1.

    I think the time complexity is 2* (log m + log n).

    You can reduce the constant, if the input array is a square (n * n), by binary searching along the diagonal.

提交回复
热议问题