LeetCode #240: Search a 2D Matrix II

Problem

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.
For example,

Consider the following 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]
]
Given target = 5, return true.

Given target = 20, return false.

Solution

题意

给定一个二维矩阵,该矩阵的行和列都是各自递增的。实现一个查找算法。

分析

由于本题的分类为Divide and Conquer,所以先考虑用递归的解法(但是不用递归代码反而更简洁)。

递归解法:

跟递归有关的首先想到的是二分查找,分析矩阵的性质可知,对于处在矩阵中心的数字x,如果:
1. target == x,查找成功,返回true
2. target > x,则以x为端点的左上角的子矩阵中一定不含target(左上角的子矩阵的值都小于x)
3. target < x,则以x为端点的右下角的子矩阵中一定不含target(右下角的子矩阵的值都大于x)
这样每递归一次就可以把查找范围缩小1/4,代码中要注意边界条件。

非递归解法:

从矩阵的左上角或者右下角开始查找,以左上角为例(此时i = 0, j = matrix[0].size() - 1),对于x = matrix[i][j]:
1. target == x,查找成功,返回true
2. target > x,则该行一定不包含target,i++
3. target < x,则该列一定不包含target,j–

Code
Version 1 - 递归版
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty())
            return false;
        int rsize = matrix.size();
        int csize = matrix[0].size();
        return aux(matrix, target, 0, rsize - 1, 0, csize - 1);
    }

    bool aux(vector<vector<int>>& matrix, int target, int rlow, int rhigh, int clow, int chigh) {
        if (rlow > rhigh || clow > chigh)
            return false;
        if (rlow == rhigh && clow == chigh)
            return matrix[rlow][clow] == target;
        int rmid = (rlow + rhigh) / 2;
        int cmid = (clow + chigh) / 2;
        if (matrix[rmid][cmid] == target)
            return true;
        else if (matrix[rmid][cmid] > target)
            return aux(matrix, target, rlow, rmid - 1, clow, chigh) || 
                   aux(matrix, target, rmid, rhigh, clow, cmid - 1);
        else
            return aux(matrix, target, rmid + 1, rhigh, clow, chigh) || 
                   aux(matrix, target, rlow, rmid, cmid + 1, chigh);
    }
};

递归时间

Version 2 - 非递归版
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty())
            return false;
        int i_max = matrix.size();
        int i = 0;
        int j = matrix[0].size() - 1;
        while (i < i_max && j >= 0) {
            int x = matrix[i][j];
            if (target == x)
                return true;
            else if (target > x)
                i++;
            else
                j--;
        }
        return false;
    }
};

非递归时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值