240. Search a 2D Matrix II (Medium)

https://leetcode.com/problems/search-a-2d-matrix-ii/

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.

Solutions

class Solution {

    // It is not recommended to adopt naive binary search since the time complexity will be n*log(n) whether you search
    // horizontally or vertically.

    // If we stand on the top-right corner of the matrix and look diagonally, it's kind of like a
    // BST, we can go through this matrix to find the target like how we traverse the BST. The computation time
    // scale will be decreased to O(n + m)

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

        int n = matrix.length, m = matrix[0].length;
        int i = 0, j = m - 1;

        while (i < n && j >= 0) {
            if (matrix[i][j] == target) {
                return true;
            }

            if (matrix[i][j] > target) {
                j--;
            } else {
                i++;
            }
        }

        return false;
    }
}

Incorrect Solutions

References

  1. https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66160/AC-clean-Java-solution
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""