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.
Example 1:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true
Meaning of the questions:
2D Matrix given, from left to right, top to bottom in ascending order, asking if it contains target 2D Matrix
Ideas: Binary Search
Stem that input has been described from left to right, top to bottom in ascending order, suggesting a strong need Binary Search
requires attention:
int midValue = matrix[mid / n][mid % n];
mid/n
It can be drawn on the first few mid n, i.e. the row Matrix
mid%n
It can be drawn on the first of several mid n, i.e. the Matrix col
Code
1 class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 if (matrix.length == 0) return false; 4 final int rowLen = matrix.length; 5 final int colLen = matrix[0].length; 6 7 int l = 0; 8 int r = rowLen * colLen -1 ; 9 10 while (l <= r) { 11 int mid = l + (r - l) / 2; 12 int midValue = matrix[mid / colLen][mid % colLen]; 13 14 if (midValue == target){ 15 return true; 16 } else if (midValue < target) { 17 l = mid + 1; 18 } else{ 19 r = mid -1; 20 } 21 } 22 return false; 23 } 24 }