Search a 2D Matrix II

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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×n矩阵中的值。 该矩阵具有以下属性:

  • 每行中的整数按从左到右的升序排序。
  • 每列中的整数按从上到下的顺序排序。

2,题目思路

对于这道题,是在一个每一行和每一列都已经排序好的矩阵中,找到target。

因为这个已经已经排序好的特点,因此,我们在进行搜索时,也是针对这一特点,即从右上角开始,逐步往左、往下进行搜索。

原因是,此时右上角的元素是比较特殊的位置,就行来说,它是第一行最大的,因此对于任何比它小的元素,一定在其左侧位置。
而对于任何比它大的元素,已经在其下方位置,当然,可能在自己所在的列,也可能在前面的所在的列内。

以这种向左、向下的顺序进行便利,最后如果到达了左下角或者超过了最左侧的列或者超过了最下方的行,则说明查找失败。

3,代码实现

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.size() == 0)
            return false;
        //从数组的右上角向左、向下遍历
        int col = matrix[0].size()-1;
        int row = 0;
        
        while(col>=0 && row <= matrix.size()-1){
            if(target == matrix[row][col])
                return true;
            else if(target < matrix[row][col])
                col--;
            else if(target > matrix[row][col])
                row++;
        }
        return false;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值