leetcode刷题面试题 10.09. 排序矩阵查找

题目描述:给定M×N矩阵,每一行、每一列都按升序排列,请编写代码找出某元素。

示例:

现有矩阵 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]
]

给定 target = 5,返回 true

给定 target = 20,返回 false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sorted-matrix-search-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:一次变量,时间复杂度O(N),空间复杂度O(1)

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty()) {
            return false;
        }
        int m = matrix.size()-1;
        int n = matrix[0].size()-1;
        if(target < matrix[0][0]) return false;
        if(target > matrix[m][n]) return false;
        for(int i=0; i<=m;i++){
            for(int j=0; j<=n;j++){
                if(target == matrix[i][j]) return true;
                if(target > matrix[i][j]){
                    continue;
                }else break;
            }

        }
        return false;
    }
};
发布了29 篇原创文章 · 获赞 0 · 访问量 486

猜你喜欢

转载自blog.csdn.net/weixin_43022263/article/details/104450365