LeetCode 240. Leetcode 240 二维数组中的查找 (二分写法)
原题链接
中等
作者:
陈叔健爱学习
,
2022-06-13 21:30:22
,
所有人可见
,
阅读 1610
C++ 代码
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty()) return false;
int m = matrix.size(), n = matrix[0].size();
int up = 0, down = m - 1, left = 0, right = n - 1;
int l, r;
while (left < right || up < down)
{
int new_left, new_right, new_up, new_down;
l = left, r = right;
while (l < r)
{
int mid = l + r >> 1;
if (matrix[down][mid] >= target) r = mid;
else l = mid + 1;
}
new_left = l;
l = left, r = right;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (matrix[up][mid] <= target) l = mid;
else r = mid - 1;
}
new_right = l;
l = up, r = down;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (matrix[mid][new_left] <= target) l = mid;
else r = mid - 1;
}
new_down = l;
l = up, r = down;
while (l < r)
{
int mid = l + r >> 1;
if (matrix[mid][new_right] >= target) r = mid ;
else l = mid + 1;
}
new_up = l;
if (new_left == left && new_right == right && new_up == up && new_down == down)
return true; //如果都不变的话 则是答案 返回即可
//更新答案
left = new_left, right = new_right;
up = new_up, down = new_down;
}
return matrix[up][left] == target;
}
};