74. Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
在一个m*n二维数组中,每一行从左到右递增,每一行的第一个元素比上一行最后一个元素大。
判断某个元素是否在 该数组中。
1 public boolean searchMatrix(int[][] matrix, int target) { 2 if (matrix.length == 0 || matrix[0].length == 0) return false; 3 if (target < matrix[0][0] || target > matrix[matrix.length - 1][matrix[0].length - 1]) return false; 4 int m = matrix.length; 5 int n = matrix[0].length; 6 int left = 0, right = m * n - 1; 7 while (left < right) { 8 int mid = left + (right - left) / 2; 9 if (matrix[mid / n][mid % n] == target) return true; 10 else if (matrix[mid / n][mid % n] > target) right = mid - 1; 11 else left = mid + 1; 12 } 13 return matrix[left / n][left % n] == target; 14 }