[Likou] 74. Search two-dimensional matrix
Given an mxn matrix of integers satisfying the following two properties:
- The integers in each row are in non-decreasing order from left to right.
- The first integer in each row is greater than the last integer in the previous row.
Given an integer target, if target is in the matrix, return true; otherwise, return false.
Example 1:
1 | 3 | 5 | 7 |
---|---|---|---|
10 | 11 | 16 | 20 |
23 | 30 | 34 | 60 |
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2:
1 | 3 | 5 | 7 |
---|---|---|---|
10 | 11 | 16 | 20 |
23 | 30 | 34 | 60 |
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
- 1 0 4 10^4 104 <= matrix[i][j], target <= 1 0 4 10^4 104
answer
Dichotomy improvement, mapping a two-dimensional array to a one-dimensional array for dichotomy
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return false;
}
int row = matrix.length;
int col = matrix[0].length;
int left = 0;
int right = row * col - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// (x,y) --> x*col+y
//反过来:一维转二维:matrix[mid/col][mid%col]
int element = matrix[mid / col][mid % col];
if (element == target) {
return true;
}
else if (element > target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return false;
}
}