经典面试题:有序矩阵的快速查找

【编者案】算法核心不在于框架用得有多熟练,更多在于逻辑和思维方式,很多情况都需要变换间接建模。本文将通过一个经典的面试题来描述思维过程,引导最终问题建模。
接着面试官要开始放大招了。
2.2逐行二分
一维的可以用二分快速查找,那就分解成一维,一行一行的用二分不就行了吗。












bool solve1(vector<vector<int>> &matrix, ofstream &cout, int x) {
int i, j;
i = 0;
j = matrix[0].size() - 1;
bool flag = false;
while (i < matrix[0].size() && j >= 0) {
if (matrix[i][j] > x) {
--j;
} else if (matrix[i][j] < x) {
++i;
} else {
return true;
}
}
return false;
}

按行二分,缩小列
int searchColumn(vector<vector<int>> &matrix, int up, int right, int x) {
int i, j, mid;
i = 0;
j = right;
while (i < j) {
mid = (i + j) / 2;
if (x < matrix[up][mid]) {
j = mid - 1;
} else if (x > matrix[up][mid]) {
i = mid + 1;
} else {
i = j = mid;
}
}
if (matrix[up][i] > x) --i;
return i;
}
int searchRow(vector<vector<int>> &matrix, int up, int right, int x) {
int i, j, mid;
i = up;
j = matrix.size() - 1;
while (i < j) {
mid = (i + j) / 2;
if (x < matrix[mid][right]) {
j = mid - 1;
} else if (x > matrix[mid][right]) {
i = mid + 1;
} else {
i = j = mid;
}
}
if (matrix[i][right] < x) ++i;
return i;
}
bool solve2(vector<vector<int>> &matrix, ofstream &cout, int x) {
int up, right;
up = 0;
right = matrix[0].size() - 1;
while (!(up == matrix.size() || right < 0)) {
right = searchColumn(matrix, up, right, x);
if (right < 0) continue;
up = searchRow(matrix, up, right, x);
if (up == matrix.size())continue;
if (matrix[up][right] == x) {
return true;
}
}
return false;
}
void dataInit() {
ofstream cout("a.in");
int s = 0;
for (int i = 0; i < 5000; ++i) {
for (int j = 0; j < 5000; ++j) {
cout << s + i + j << " ";
}
s += 4999;
cout << endl;
}
}
目标数:10002500
线性执行效率:
row=2000, column=2500
T1=288
二分执行效率
row=2000, column=2500
T2=10
☞C 和 C++ 不安全?Android 支持 Rust 开发操作系统
☞16岁的雅虎问答,因“不再受欢迎”将永久关闭
☞滴滴、小米启动造车,特斯拉的护城河还能守多久?
[广告]赞助链接:
关注数据与安全,洞悉企业级服务市场:https://www.ijiandao.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
- iTrustSSL:选择SSL证书时,不同品牌的区别是?
- 飞书企业邮箱 免费安全的企业团队协作办公邮箱
- AiEditor:面向AI的下一代富文本编辑器
- 周星驰 Web3 团队将上线独立 App;Gemini 刚发就惹质疑:效果视频疑似剪辑;Meta 推独立AI图像生成器|极客头条
- “53 岁的我都退休了,但好想跨行当一名程序员,结果收到了 3 份 Offer!”
- 百度下线搜索快照功能,内部人士:因技术升级导致功能淘汰;法国App开发者集体起诉苹果;Linux 5.19 发布|极客头条
- 前中情局程序员因向维基解密泄露中情局黑客工具被定罪
- 从预测到决策,九章云极DataCanvas 推出 YLearn 因果学习开源项目
- realityOS会是苹果的新操作系统吗?
- 诸子云 | 活动:11.13深圳金融行业专场沙龙
- 有赞个性化推荐能力的演进与实践
- CSDN湘苗培优,遇见更好的自己
赞助链接