且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[CareerCup] 11.6 Search a 2D Matrix 搜索一个二维矩阵

更新时间:2022-09-19 17:32:46

11.6 Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.

LeetCode上的原题,请参见我之前的博客Search a 2D Matrix 搜索一个二维矩阵Search a 2D Matrix II 搜索一个二维矩阵之二

class Solution {
public:
    bool findElement(vector<vector<int> > &matrix, int elem) {
        if (matrix.empty() || matrix[0].empty()) return false;
        int row = 0, col = matrix[0].size() - 1;
        while (row < matrix.size() && col >= 0) {
            if (matrix[row][col] == elem) return true;
            else if (matrix[row][col] < elem) ++row;
            else --col;
        }
        return false;
    }
};

 本文转自博客园Grandyang的博客,原文链接:搜索一个二维矩阵[CareerCup] 11.6 Search a 2D Matrix ,如需转载请自行联系原博主。