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