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

125人阅读 评论(0)

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;
}

};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：7136次
• 积分：373
• 等级：
• 排名：千里之外
• 原创：31篇
• 转载：3篇
• 译文：0篇
• 评论：0条
阅读排行