Search a 2D Matrix
2017-02-13 23:15
176 查看
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:
Given target =
bool fun(vector<vector<int> > &a, int target)
{
int m = a.size();
int n = a[0].size();
int top = 0;
int bottom = m-1;
int row = -1;
while (top <= bottom)
{
int mid = top + (bottom-top)/2;
if (target <= a[mid][n-1] && target >= a[mid][0])
{
row = mid;
break;
}
else if (target > a[mid][n-1])
{
top = mid+1;
}
else if (target < a[mid][n-1])
{
bottom = mid-1;
}
}
if (row == -1)
{
return false;
}
int left = 0;
int right = n-1;
while (left <= right)
{
int mid = left + (right-left)/2;
if (a[row][mid] == target)
{
return true;
}
else if (target < a[row][mid])
{
right = mid-1;
}
else
{
left = mid+1;
}
}
return false;
}
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.
bool fun(vector<vector<int> > &a, int target)
{
int m = a.size();
int n = a[0].size();
int top = 0;
int bottom = m-1;
int row = -1;
while (top <= bottom)
{
int mid = top + (bottom-top)/2;
if (target <= a[mid][n-1] && target >= a[mid][0])
{
row = mid;
break;
}
else if (target > a[mid][n-1])
{
top = mid+1;
}
else if (target < a[mid][n-1])
{
bottom = mid-1;
}
}
if (row == -1)
{
return false;
}
int left = 0;
int right = n-1;
while (left <= right)
{
int mid = left + (right-left)/2;
if (a[row][mid] == target)
{
return true;
}
else if (target < a[row][mid])
{
right = mid-1;
}
else
{
left = mid+1;
}
}
return false;
}
相关文章推荐
- Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix 解题报告
- leetcode 90: Search a 2D Matrix
- [LeetCode] Search a 2D Matrix [25]
- Search a 2D Matrix
- [leetcode]74. Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Search a 2D Matrix
- (二维数组中查找target)LeetCode#74. Search a 2D Matrix #240. Search a 2D Matrix II
- [leetcode] 74. Search a 2D Matrix 解题报告
- leetcode 74. Search a 2D Matrix
- Search a 2D Matrix
- 【leetcode】Array——Search a 2D Matrix(74)
- LeetCode 74 Search a 2D Matrix(Python详解及实现)
- leetcode:Search a 2D Matrix 【Java】
- leetcode之Search a 2D Matrix
- Search a 2D Matrix
- 74. Search a 2D Matrix