一、问题描述:
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 * (m*N)的数组,第k个位置对应到矩阵的[k/n][k%n]
三、代码:
package T12;
/**
* @author 作者 : xcy
* @version 创建时间:2016年12月22日 下午11:48:33
* 类说明
*/
public class t74 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] matrix = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
int target = 51;
System.out.println(searchMatrix(matrix, target));
}
public static boolean searchMatrix(int[][] matrix, int target) {
boolean flag = false;
int m = matrix.length;
if(m==0){
return false;
}
int n = matrix[0].length;
int num = m * n;
int start = 0;
int end = num;
int x = 0;
int y = 0;
int mid = 0;
while (start < end) {
mid = (start + end) / 2;
x = mid / n;
y = mid % n;
if (target == matrix[x][y]) {
return true;
}
if (target < matrix[x][y]) {
end = start + (end - start) / 2;
}
if (target > matrix[x][y]) {
start = end - (end - start) / 2;
}
}
return flag;
}
}