Leetcode JAVA刷刷站(74)搜索二维矩阵

时间:2025-04-07 21:08:18
  • 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;
  • }
  • // 辅助函数,根据二维数组的索引(转换为一维数组的索引)来获取元素值
  • // row 和 col 分别是二维数组的行和列索引
  • 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)); // 输出 true
  • target = 20;
  • ((matrix, target)); // 输出 true
  • target = 22;
  • ((matrix, target)); // 输出 false
  • }
  • }