leetcode 240. 搜索二维矩阵 II medium

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/speargod/article/details/98540341

leetcode 240. 搜索二维矩阵 II  medium          

题目描述:

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

解题思路:

注意跟上一题的区别(这一题不是二分)

从右上角or左下角开始搜即可

代码:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty() || matrix[0].empty())
            return false;
        
        // 从右上角开始搜
        int row=matrix.size();
        int col=matrix[0].size();
        int i=0,j=col-1;
        
        while(i<row && j>=0){
            if(matrix[i][j]<target)
                ++i;
            else if(matrix[i][j]>target)
                --j;
            else
                return true;
        }
        
        return false;
        
        
    }
};

猜你喜欢

转载自blog.csdn.net/speargod/article/details/98540341