Search a 2D Matrix

lc 74

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.
Example 1:

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

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return false;
        int width = matrix[0].length;
        int length = matrix.length;
        int start = 0;
        int end = width * length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int xMid = mid / width;
            int yMid = mid % width;
            if (matrix[xMid][yMid] == target) {
                return true;
            } else if (matrix[xMid][yMid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        int xStart = start / width;
        int yStart = start % width;

        if (matrix[xStart][yStart] == target) return true;

        int xEnd = end / width;
        int yEnd = end % width;

        if (matrix[xEnd][yEnd] == target) return true; 
        return false;

    }
}

LC 240

  1. Search a 2D Matrix II Medium

1546

44

Favorite

Share 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 in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. Example:

Consider the following matrix:

[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true.

Given target = 20, return false.

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int i = 0;
        int j = matrix[0].length - 1;
        while (j >= 0 && i < matrix.length) {
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] > target) {
                j--;
            } else {
                i++;
            }
        }
        return false;
    }
}

results matching ""

    No results matching ""