[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.

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.

分析

这个题目其实使用暴力搜索的办法估摸着应该不是出题者的本意,遍历行或者列在每行或者每列中做二分查找时间复杂度为m * logn 或者n * logm。

我也是看到了网上别人的很巧妙的解法,其实可以从二维数组的左下角开始寻找,如果matrix[i][j]大于target,那么可以断定[0,i][0,j]的范围([i][j]的左上角)内一定没有target,因为这个范围的数都是比他小的。那么就向右寻找target,即j ++。如果matrix[i][j] > target,那么说明[i][j]的右下角一定没有target,就向上寻找,即i--。

Code

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int row = matrix.size();
        if (row == 0)
            return false;
        int col = matrix[0].size();
        
        int i = row - 1;
        int j = 0;
        
        while (i >= 0 && j < col)
        {
            if (matrix[i][j] == target)
                return true;
            if (matrix[i][j] > target)
            {
                i --;
            }
            else if (matrix[i][j] < target)
            {
                j ++;
            }
        }
        
        return false;
    }
};

运行效率

Runtime: 92 ms, faster than 35.38% of C++ online submissions for Search a 2D Matrix II.

Memory Usage: 13 MB, less than 5.28% of C++ online submissions for Search a 2D Matrix II.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值