Most efficient way to search a sorted matrix?

后端 未结 9 1470
野的像风
野的像风 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:33

    in log M you can get a range of rows able to contain the target (binary search on the first value of rows, binary search on last value of rows, keep only those rows whose first <= target and last >= target) two binary searches is still O(log M)
    then in O(log N) you can explore each of these rows, with again, a binary search!

    that makes it O(logM x logN)
    tadaaaa

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-29 14:41

    Your matrix looks like this:

    a ..... b ..... c
    . .     . .     .
    .   1   .   2   . 
    .     . .     . .
    d ..... e ..... f
    . .     . .     .
    .   3   .   4   .
    .     . .     . .
    g ..... h ..... i
    

    and has following properties:

    a,c,g < i  
    a,b,d < e
    b,c,e < f
    d,e,g < h
    e,f,h < i
    

    So value in lowest-rigth most corner (eg. i) is always the biggest in whole matrix and this property is recursive if you divide matrix into 4 equal pieces.

    So we could try to use binary search:

    1. probe for value,
    2. divide into pieces,
    3. choose correct piece (somehow),
    4. goto 1 with new piece.

    Hence algorithm could look like this:

    input: X - value to be searched
    until found
     divide matrix into 4 equal pieces
     get e,f,h,i as shown on picture
     if (e or f or h or i) equals X then 
       return found
     if X < e then quarter := 1
     if X < f then quarter := 2
     if X < h then quarter := 3
     if X < i then quarter := 4
     if no quarter assigned then 
        return not_found
     make smaller matrix from chosen quarter 
    

    This looks for me like a O(log n) where n is number of elements in matrix. It is kind of binary search but in two dimensions. I cannot prove it formally but resembles typical binary search.

    0 讨论(0)
提交回复
热议问题