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

后端 未结 20 1096
暖寄归人
暖寄归人 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:22

    The optimal solution is to start at the top-left corner, that has minimal value. Move diagonally downwards to the right until you hit an element whose value >= value of the given element. If the element's value is equal to that of the given element, return found as true.

    Otherwise, from here we can proceed in two ways.

    Strategy 1:

    1. Move up in the column and search for the given element until we reach the end. If found, return found as true
    2. Move left in the row and search for the given element until we reach the end. If found, return found as true
    3. return found as false

    Strategy 2: Let i denote the row index and j denote the column index of the diagonal element we have stopped at. (Here, we have i = j, BTW). Let k = 1.

    • Repeat the below steps until i-k >= 0
      1. Search if a[i-k][j] is equal to the given element. if yes, return found as true.
      2. Search if a[i][j-k] is equal to the given element. if yes, return found as true.
      3. Increment k

    1 2 4 5 6
    2 3 5 7 8
    4 6 8 9 10
    5 8 9 10 11

提交回复
热议问题