#include <stdbool.h>
bool searchMatrix(int **matrix, int matrixSize, int *matrixColSize, int target) {
int rows = matrixSize, cols = matrixColSize[0];
int left = 0, right = rows * cols - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int i = mid / cols, j = mid % cols;
if (matrix[i][j] == target)
return true;
if (matrix[i][j] > target)
right = mid - 1;
else
left = mid + 1;
}
return false;
}
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>> &matrix, int target) {
int rows = matrix.size();
int cols = matrix[0].size();
int left = 0, right = rows * cols - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int i = mid / cols;
int j = mid % cols;
if (matrix[i][j] == target)
return true;
if (matrix[i][j] > target)
right = mid - 1;
else
left = mid + 1;
}
return false;
}
};
package main
func searchMatrix(matrix [][]int, target int) bool {
rows, cols := len(matrix), len(matrix[0])
left, right := 0, rows*cols-1
for left <= right {
mid := left + (right-left)/2
i, j := mid/cols, mid%cols
if matrix[i][j] == target {
return true
}
if matrix[i][j] > target {
right = mid - 1
} else {
left = mid + 1
}
}
return false
}
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length, cols = matrix[0].length;
int left = 0, right = rows * cols - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int i = mid / cols, j = mid % cols;
if (matrix[i][j] == target)
return true;
if (matrix[i][j] > target)
right = mid - 1;
else
left = mid + 1;
}
return false;
}
}
class Solution {
searchMatrix(matrix, target) {
const rows = matrix.length, cols = matrix[0].length;
let left = 0, right = rows * cols - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
const i = Math.floor(mid / cols), j = mid % cols;
if (matrix[i][j] === target) return true;
if (matrix[i][j] > target) right = mid - 1;
else left = mid + 1;
}
return false;
}
}
class Solution:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
rows, cols = len(matrix), len(matrix[0])
left, right = 0, rows * cols - 1
while left <= right:
mid = left + (right - left) // 2
i, j = divmod(mid, cols)
if matrix[i][j] == target:
return True
if matrix[i][j] > target:
right = mid - 1
else:
left = mid + 1
return False
struct Solution;
impl Solution {
fn search_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
let (rows, cols) = (matrix.len(), matrix[0].len());
let (mut left, mut right) = (0i32, (rows * cols) as i32 - 1);
while left <= right {
let mid = left + (right - left) / 2;
let (i, j) = ((mid as usize) / cols, (mid as usize) % cols);
if matrix[i][j] == target {
return true;
}
if matrix[i][j] > target {
right = mid - 1;
} else {
left = mid + 1;
}
}
false
}
}