欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 74. Search a 2D Matrix

程序员文章站 2022-07-14 17:53:45
...

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 from left to right.The first integer of each row is greater than the last integer of the previous row.
Example 1:Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int i=0;
        int m = matrix.size();
        if (!m) return false;
        int n = matrix[0].size();
        if (!n) return false;
        if(target<matrix[0][0]||target>matrix[m-1][n-1])
            return false;
        for(i=0;i<m;i++){
            if(target>=matrix[i][0]&&target<=matrix[i][n-1])
                break;
        }
        if(i==m)  //注意,如果夹在矩阵两行之间,那么遍历之后会越界,这里需要判断一下
            return false;
        for(int j=0;j<n;j++)
            if(target==matrix[i][j])
                return true;
        return false;
    }
};
相关标签: LeetCode