Skip to content

74. Search a 2D Matrix

You are given an m x n integer matrix matrix with the following two properties:

  • Each row is sorted in non-decreasing order.
  • The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return true if target is in matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

Example 1:

img

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

Example 2:

img

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

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

Solution:

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix[0].length == 0){
            return false;
        }

        for (int i = 0; i < matrix.length; i++){
            boolean result = binarySearch(matrix[i], target);
            if (result == true){
                return true;
            }
        }   
        return false;
    }

    public static boolean binarySearch(int[] array, int target){
        int left = 0; 
        int right = array.length -1;
        while (left <= right){
            int mid = left + (right - left)/2;
            if (array[mid] == target){
                return true;
            }else if (array[mid] < target){
                left = mid + 1;
            }else if (array[mid] > target){
                right = mid - 1;
            } 
        }

        return false;
    }
}

// TC O(nlogn)
// SC O(1)