题目

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. [
  2. [1, 4, 7, 11, 15],
  3. [2, 5, 8, 12, 19],
  4. [3, 6, 9, 16, 22],
  5. [10, 13, 14, 17, 24],
  6. [18, 21, 23, 26, 30]
  7. ]

Given target = 5, return true.

Given target = 20, return false.


题意

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

思路

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

分治法:从矩阵的左下角元素X出发,根据矩阵的性质,如果target>X,以X作一条垂直线,则target只可能在该线右侧的矩阵里;如果target<X,以X作一条水平线,则target只可能在该线上侧的矩阵里。因此每次都可以将问题转化为在一个更小的矩阵里找到target。当然也可以以矩阵的右上角元素作为起点。时间复杂度为0240. Search a 2D Matrix II (M) - 图2#card=math&code=O%28M%2BN%29)。


代码实现

Java

二分法

  1. class Solution {
  2. public boolean searchMatrix(int[][] matrix, int target) {
  3. if (matrix.length == 0 || matrix[0].length == 0) {
  4. return false;
  5. }
  6. int m = matrix.length, n = matrix[0].length;
  7. for (int i = 0; i < m; i++) {
  8. if (matrix[i][n - 1] < target) {
  9. continue;
  10. } else if (matrix[i][0] > target) {
  11. break;
  12. } else {
  13. int left = 0, right = n - 1;
  14. while (left <= right) {
  15. int mid = (right - left) / 2 + left;
  16. if (matrix[i][mid] < target) {
  17. left = mid + 1;
  18. } else if (matrix[i][mid] > target) {
  19. right = mid - 1;
  20. } else {
  21. return true;
  22. }
  23. }
  24. }
  25. }
  26. return false;
  27. }
  28. }

分治法

  1. class Solution {
  2. public boolean searchMatrix(int[][] matrix, int target) {
  3. if (matrix.length == 0 || matrix[0].length == 0) {
  4. return false;
  5. }
  6. int m = matrix.length, n = matrix[0].length;
  7. int i = m - 1, j = 0;
  8. while (i >= 0 && j < n) {
  9. if (matrix[i][j] < target) {
  10. j++;
  11. } else if (matrix[i][j] > target) {
  12. i--;
  13. } else {
  14. return true;
  15. }
  16. }
  17. return false;
  18. }
  19. }

JavaScript

  1. /**
  2. * @param {number[][]} matrix
  3. * @param {number} target
  4. * @return {boolean}
  5. */
  6. var searchMatrix = function (matrix, target) {
  7. const m = matrix.length
  8. const n = matrix[0].length
  9. let i = m - 1
  10. let j = 0
  11. while (i >= 0 && j < n) {
  12. if (matrix[i][j] < target) {
  13. j++
  14. } else if (matrix[i][j] > target) {
  15. i--
  16. } else {
  17. return true
  18. }
  19. }
  20. return false
  21. }