Search A 2D Matrix

06/28/2016 Array Binary Search

Question

Write an efficient algorithm that searches for a value in an matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example, Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given = 3, return true.


Solution

Result: Accepted Time: 8 ms

Here should be some explanations.

bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) {
    register int dx = matrixRowSize - 1,dy = 0,tmp,tar=target;
    while(dy < matrixColSize && dx >= 0)
    {
        tmp = matrix[dx][dy];
        if(tar == tmp) return true;
        if(tar > tmp)
            ++dy;
        else
            --dx;
    }
    return false;
}

Complexity Analytics

  • Time Complexity:
  • Space Complexity: