Problem Description:
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
Example 2:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false
Analysis:
本题的思路就是使用二分法,我使用的方法是将每行看做一个分段,先确定target值是在哪一行,然后再使用二分搜索的方法寻找确切的元素。代码如下:
Code:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
if(row < 1)
return false;
int col = matrix[0].length;
if(col < 1)
return false;
System.out.println(row + ", " + col);
for(int i = 0; i < row; i++) {
if(matrix[i][0] <= target && target <= matrix[i][col - 1]) {
int s = 0, t = col - 1;
while(s <= t) {
int mid = (s + t)/2;
if(matrix[i][mid] < target) {
s = mid + 1;
} else if(matrix[i][mid] > target) {
t = mid - 1;
} else {
return true;
}
}
}
}
return false;
}
}