class Solution: def search_matrix(self, matrix, target): # Find the first position of target if not matrix or not matrix[0]: return False 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: return True 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
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false;
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) return true; ub = mid; } } return false; } };
public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0] == null) { return false; }
int ROW = matrix.length, COL = matrix[0].length; 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) { return true; } ub = mid; } }