# 【Leet Code】74. Search a 2D Matrix---Medium

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.

class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() < 1 || matrix[0].size() < 1) return false;
int up = 0, down = matrix.size()-1;
int mid = 0;
while(up <= down)
{
mid = (up + down)/2;
if(searchArray(matrix[mid], target)) return true;

if(target < matrix[mid][0]) down = mid -1;
else up = mid + 1;
}
return false;
}
private:
bool searchArray(vector<int>& nums, int target){
int left = 0, right = nums.size() -1;
int mid = 0;
while(left <= right)
{
mid = (left + right)/2;
if(target == nums[mid])
return true;
if(target > nums[mid])
left = mid + 1;
else right = mid - 1;
}
return false;
}

};

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

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