leetcode hot 100-240. 搜索二维矩阵 II

240. 搜索二维矩阵 II

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

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

现有矩阵 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] ]

给定 target = 5,返回 true。

给定 target = 20,返回 false。

思路:

从矩阵的左下角开始遍历
如果当前元素小于目标值,往右移一格,如果大于目标值,往上移一格,如果相等,直接返回true
 1 class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) {
 3 
 4         if(matrix.length == 0 || matrix[0].length == 0){
 5             return false;
 6         }
 7         int rows = matrix.length;
 8         int cols = matrix[0].length;
 9         int i = rows - 1, j = 0;
10         while(i >= 0 && j < cols){
11             if(target > matrix[i][j]){
12                 j++;
13             }else if(target < matrix[i][j]){
14                 i--;
15             }else{
16                 return true;
17             }
18         }
19         return false;
20     }
21 }
leetcode 执行用时:6 ms > 97.00%, 内存消耗:43.7 MB > 97.03%

复杂度分析:

时间复杂度:O(m+n)。每次会向上或者向右移动一个,所以最坏情况下向上移动 m 格,向右移动 n 格,所以最坏情况下的时间复杂度为O(m+n)。
空间复杂度:O(1)。只需要常数个变量的空间,所以空间复杂度为O(1)。
原文地址:https://www.cnblogs.com/hi3254014978/p/13887824.html