剑指offer(第二版)面试题4. 二维数组中的查找,leetcode 240. Search a 2D Matrix II

欢迎访问我的剑指offer(第二版)题解目录
对应的leetcode题目可点击leetcode 240. 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.

算法设计

参考书中的算法:

首先选取数组中右上角的数字。如果该数字等于要查找的数字,则查找过程结束;如果该数字大于要查找的数字,则剔除这个数字所在的列:如果该数字小于要查找的数字,则剔除这个数字所在的行。也就是说,如果要查找的数字不在数组的右上角,则每一次都在数组的查找范围中剔除一行或者一列,这样每一步都可以缩小查找的范围,直到找到要查找的数字,或者查找范围为空。

整个算法的时间复杂度为 O ( m + n ) O(m+n) ,空间复杂度为 O ( 1 ) O(1)

C++代码

class Solution {
   public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty())
            return false;
        int m = matrix.size(), n = matrix[0].size();
        for (int i = 0, j = n - 1; i < m and j >= 0;) {
            if (matrix[i][j] == target)
                return true;
            else if (matrix[i][j] > target)
                --j;
            else
                ++i;
        }
        return false;
    }
};
发布了528 篇原创文章 · 获赞 1015 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/richenyunqi/article/details/103384871