- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
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] ]
Given target = 3, return true.
/*
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]
]
Given target = 3, return true.
*/
// Brute force solution
bool search(vector<vector<int> > &mtx, int x)
{
int i=0;
for(; i<mtx.size(); i++)
{
if(x<mtx[i][0]) //
{
break;
}
}
if(i==0) return false;
i--;
for(int j=0; j<m[i].size(); j++)
{
if(m[i][j]==x) return true;
}
return false;
}
int upper_bound(vector<int> &m, int x)
{
int l=0, u=m.size();
while(l<u-1)
{
int mid = l + (u-l)/2;
if(m[mid]<=x) // assume that: 1 1 1 1 1 1 1 1 2, find 1
{
l=mid;
}
else // m[mid] < x
{
h=mid-1;
}
}
return l;
}
int lower_bound(vector<int> &m, int x)
{
int l=0, u=m.size();
while(l<u-1)
{
int mid = l + (u-l)/2;
if(m[mid]<=x) // assume that: 0 1 1 1 1 1 1 1, find 1
{
u=mid;
}
else // x < m[mid]
{
l=mid+1;
}
}
return l;
}
本文探讨了在具有特定排序属性的二维矩阵中查找目标值的高效算法,通过边界用例和特殊用例分析,提供了从暴力解到优化的详细过程,并结合伪代码和实际代码演示了最优解决方案。
403

被折叠的 条评论
为什么被折叠?



