0240. Search a 2D Matrix II (M)

Search a 2D Matrix II (M)

题目

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.


题意

判断在一个行元素递增、列元素也递增的矩阵中能否找到目标值。

思路

二分法:本来想着先用二分找到行数的下界,但发现即使找到了下界down,也需要再重新遍历 0 - (down-1) 这些行,对每行进行二分查找。这样不如直接从上到下遍历所有行,如果当前行行尾元素小于target,说明该行可以跳过;如果当前行行首元素大于target,说明剩余行不可能存在target,可以直接跳出循环;其余情况则对当前行进行二分查找。时间复杂度为\(O(MlogN)\)

分治法:从矩阵的左下角元素X出发,根据矩阵的性质,如果target>X,以X作一条垂直线,则target只可能在该线右侧的矩阵里;如果target<X,以X作一条水平线,则target只可能在该线上侧的矩阵里。因此每次都可以将问题转化为在一个更小的矩阵里找到target。当然也可以以矩阵的右上角元素作为起点。时间复杂度为\(O(M+N)\)


代码实现

Java

二分法

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

        int m = matrix.length, n = matrix[0].length;

        for (int i = 0; i < m; i++) {
            if (matrix[i][n - 1] < target) {
                continue;
            } else if (matrix[i][0] > target) {
                break;
            } else {
                int left = 0, right = n - 1;
                while (left <= right) {
                    int mid = (right - left) / 2 + left;
                    if (matrix[i][mid] < target) {
                        left = mid + 1;
                    } else if (matrix[i][mid] > target) {
                        right = mid - 1;
                    } else {
                        return true;
                    }
                }
            }
        }

        return false;
    }
}

分治法

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

        int m = matrix.length, n = matrix[0].length;

        int i = m - 1, j = 0;

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

        return false;
    }
}

JavaScript

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function (matrix, target) {
  const m = matrix.length
  const n = matrix[0].length

  let i = m - 1
  let j = 0

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

  return false
}
posted @ 2021-02-23 16:24  墨云黑  阅读(38)  评论(0编辑  收藏  举报