L74 Search a 2D Matrix

Binary Search

Problem:

Write an efficient algorithm that searches for a value in an m x n 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.

  • matrix 展开后是一个sorted array.

Example:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Solution:

  • mid / col --> find the row index

  • mid % col --> find the col index

public boolean searchMatrix(int[][] matrix, int target){
    if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return false;
    int row = matrix.length, col = matrix[0].length;
    int left = 0, right = row * col - 1;
    while(left <= right){
        int mid = left + (right - left) / 2;
        int r = mid / col;
        int c = mid % col;
        if(matrix[r][c] == target) return true;
        else if(matrix[r][c] > target) right = mid - 1;
        else left = mid + 1;
    }
    return false;
}

Last updated

Was this helpful?