Search a 2D Matrix

本文介绍了一种高效的算法,用于在一特殊类型的m*n矩阵中查找特定数值。该矩阵的特点是每行每列都按升序排列。文章提供了三种不同的解决思路:线性扫描、改进的线性搜索及二分查找,并附带C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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 from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

分析

1. 题目要求

给出一个m * n矩阵,该矩阵每一行都是从小到大排列,每一列也是如此。找出该矩阵中是否含有给出的目标数。

2. 求解思路

1. 最简单的方法,可以从左到右,从上到下依次遍历整个矩阵看是否含有目标数,但时间复杂度为 O(mn)。

2. 由于已经排好序了,我们可以依次将每一行的第一个元素和目标数作比较,找出目标数可能在的行数。

    再将该行的每一个元素和目标数作比较,看是否含有目标数。时间复杂度为 O(m + n)。

3. 其实这个与一维已排序数组查找目标数差不多,可以使用二分查找的方法来求解。

   先使用二分查找(每次与中间的那一行作比较),找到目标数可能在的那一行。

   再继续对目标行使用二分查找,看是否含有目标数。 时间复杂度为 O( log(mn) )。

3. 代码如下

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty()) return false;
        int m = matrix.size();
        int n = matrix[0].size();
        int a = 0;
        int b = m - 1;
        int index = (b + a) / 2;
        while (b >= a) {
            if (matrix[index][0] <= target && matrix[index][n-1] >= target) {
                for (int i = 0; i < n; i++) {
                    if (matrix[index][i] == target) return true;
                }
                int c = 0, d = n - 1;
                int mid = (c + d) / 2;
                while (d >= c) {
                    if (matrix[index][mid] == target) {
                        return true;
                    } else if (matrix[index][mid] < target) {
                        c = mid + 1;
                        mid = (c + d) / 2;
                    } else {
                        d = mid - 1;
                        mid = (c + d) / 2;
                    }
                }
                return false;
            } else if (matrix[index][0] > target) {
                b = index - 1;
                index = (b + a) / 2;
            } else if (matrix[index][n-1] < target) {
                a = index + 1;
                index = (b + a) / 2;
            }
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值