# Middle-题目36：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]
]

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int start = 0,end = matrix.length - 1,mid;
if(start == end) // the matrix has only 1 line
return binarySeach(matrix[0],target);
while(start <= end) {
mid = (start + end) / 2;
if(matrix[mid][0] == target)
return true;
else if(matrix[mid][0] < target && (mid == matrix.length-1 || matrix[mid+1][0] > target)) // target may be at line of mid
return binarySeach(matrix[mid],target);
else if(matrix[mid+1][0] <= target)   //target lies after line of mid
start = mid + 1;
else
end = mid-1;
}
return false;
}
private  boolean binarySeach(int[] nums, int target) {
int start = 0, end = nums.length-1, mid;
while(start <= end) {
mid = (start + end) / 2;
if(nums[mid] == target)
return true;
else if(nums[mid] < target)
start = mid + 1;
else
end = mid - 1;
}
return false;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目36：74. Search a 2D Matrix 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)