题目描述

LeetCode 74. 搜索二维矩阵

题解

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

相关文章: