public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || == 0 || matrix[0].length == 0) {
return false;
}
int m = ;
int n = matrix[0].length;
int left = 0;
int right = m * n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int midVal = getElement(matrix, mid / n, mid % n);
if (midVal == target) {
return true;
} else if (midVal < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
// Helper function to get element values based on the index of a two-dimensional array (converted to an index of a one-dimensional array)
// row and col are row and column indices of two-dimensional arrays respectively
private int getElement(int[][] matrix, int row, int col) {
return matrix[row][col];
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] matrix = {
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 50}
};
int target = 3;
((matrix, target)); // Output true
target = 20;
((matrix, target)); // Output true
target = 22;
((matrix, target)); // Output false
}
}