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 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;
    }
};

 

相关文章:

  • 2021-08-12
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2021-08-28
  • 2022-12-23
  • 2022-01-22
  • 2021-08-31
猜你喜欢
  • 2021-12-14
  • 2022-12-23
  • 2021-06-23
  • 2021-06-24
  • 2022-12-23
  • 2021-12-03
  • 2021-05-21
相关资源
相似解决方案