classSolution: defsearch_matrix(self, matrix, target): # Find the first position of target ifnot matrix ornot matrix[0]: returnFalse m, n = len(matrix), len(matrix[0]) st, ed = 0, m * n - 1
while st + 1 < ed: mid = (st + ed) / 2 if matrix[mid / n][mid % n] == target: returnTrue elif matrix[mid / n][mid % n] < target: st = mid else: ed = mid return matrix[st / n][st % n] == target or matrix[ed / n][ed % n] == target
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: boolsearchMatrix(vector<vector<int>>& matrix, int target){ if (matrix.empty() || matrix[0].empty()) returnfalse;
int ROW = matrix.size(), COL = matrix[0].size(); int lb = -1, ub = ROW * COL; while (lb + 1 < ub) { int mid = lb + (ub - lb) / 2; if (matrix[mid / COL][mid % COL] < target) { lb = mid; } else { if (matrix[mid / COL][mid % COL] == target) returntrue; ub = mid; } } returnfalse; } };