目录

​ ​一,题目描述​​

​ ​英文描述​​

​ ​中文描述​​

​ ​示例与说明​​

​ ​二,解题思路​​

​ ​三,AC代码​​

​ ​Java​​

​ ​四,解题过程​​

​ ​第一搏​​

​ ​第二搏​​


 

一,题目描述

英文描述

Write an efficient algorithm that searches for a value target in an m x n integer matrix 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.

中文描述

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

示例与说明

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_中等

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_搜索_02

 

提示:

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_二分查找_03

 

链接:​ ​https://leetcode-cn.com/problems/search-a-2d-matrix-ii​​著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二,解题思路

参考​ ​@windliang【详细通俗的思路分析,多解法】​​

Z字形搜索,yyds!

先贴张图:

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_二分查找_04

从右上角开始遍历,很容易发现规律:

  • target大于当前位置,向下移动;
  • target小于当前位置,向左移动;

游戏结束。时间复杂度O(m+n)

为了更快的判断向左、向下移动的位置,也可以引入二分查找的思路,但是编码难度也会明显提高,感兴趣的朋友可以试一试。

三,AC代码

Java

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

四,解题过程

第一搏

逐行二分。

小技巧:

  • 切换行时可以先进行边界判断,看是直接返回false还是continue;
  • 通过边界判断后,可以确定target在该行数组内部,进而得到target的左右边界,其中右边界可以继续使用,当作下一行的右边界;

思路比较直观,二分法也是常见的模板题目了,边界不太确定的话可以在纸上画一画。

时间复杂度O(mlogn)

class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int left = 0, right = n;// 左闭右开
for (int i = 0; i < m; i++) {
// 处理边界
if (target < matrix[i][0]) return false;
if (target > matrix[i][n - 1]) continue;

// 二分查找
while (left < right) {
int mid = (left + right) / 2;
if (matrix[i][mid] < target) {
left = mid + 1;
} else if (matrix[i][mid] > target) {
right = mid;
} else {
return true;
}
}
left = 0;
}
return false;
}
}

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_中等_05

第二搏

Z字形搜索。妙不可言!

以左上角(或者右下角)作为出发点,会发现当target大于当前值时,不知道向下还是向右走;

以右上角(或者左下角)作为出发点,这个问题就可以解决了;

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_leetcode_06

LeetCode_Array_240. Search a 2D Matrix II 搜索二维矩阵 II【二分查找、Z字形查找】【Java】【中等】_Z字形搜索_07