当前位置:网站首页>搜索二维矩阵[二分巧用 + 记录不同于插入二分的解法]
搜索二维矩阵[二分巧用 + 记录不同于插入二分的解法]
2022-06-24 21:17:00 【REN_林森】
记录不同于插入二分的细节
前言
有序数组或其他,就应该紧密联系二分法。但二分法有很多细节,主要分为二分查找/二分插入寻位置。而今天刷到了该题,需求不同于二分插入寻找位置,它要寻找比target刚刚小的位置,而不是后一个。
一、搜索二维矩阵

二、记录不同于插入二分的解法
package everyday.medium;
// 搜索二维矩阵
public class SearchMatrix {
/* target:快速搜索矩阵中是否存在目标值。 矩阵每行都有一个特点,那就是有序,而且列也有序,但这个序不真实。把矩阵看成一位矩阵(平铺),答案即晓。 所以行列两次二分即可。 */
public boolean searchMatrix(int[][] matrix, int target) {
// bug1:先列再行,应该先行再列。
// 二分找target 在第几行。
int low = 0, high = matrix.length - 1;
while (low < high) {
// 这里是值得记录的地方
// 不同于插入二分,这里找的是刚好比这个数大的位置,而不是后一个位置。
// 处理方式也很简单,int mid = low + (high - low + 1 >>> 1); 配合 else low = mid;
int mid = low + (high - low + 1 >>> 1);
int midVal = matrix[mid][0];
if (midVal > target) high = mid - 1;
else low = mid;
}
// 找target 在第几列。
int col = binarySearch(matrix[low], target);
return matrix[low][col] == target;
}
private int binarySearch(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
// 取上,区别于平时的升序插入,这里要找刚好比自己小的位置。
int mid = low + (high - low + 1 >>> 1);
int midVal = nums[mid];
if (midVal > target) high = mid - 1;
else low = mid;
}
return low;
}
}
总结
1)有序与二分的紧密相连,要在头脑中紧密联系。
2)不同于插入二分的解法。
参考文献
[1] LeetCode 搜索二维矩阵
边栏推荐
- vb学习什么[通俗易懂]
- Bi-sql top
- Assembly language (3) 16 bit assembly basic framework and addition and subtraction loop
- 明日考试 最后一天如何备考?二造考点攻略全整理
- Library management system code source code (php+css+js+mysql) complete code source code
- yasea apk 下载 镜像
- The latest QQ wechat domain name anti red PHP program source code + forced jump to open
- JS Chapter 1 Summary
- Première application de l'informatique quantique à la modélisation des flux de puissance dans les systèmes énergétiques à l'Université technique danoise
- Bi-sql index
猜你喜欢

粉丝福利,JVM 手册(包含 PDF)

丹麦技术大学首创将量子计算应用于能源系统潮流建模

Abnova丨5-甲基胞嘧啶多克隆抗体中英文说明

Bi-sql Union

Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?

扎克伯格上手演示四款VR头显原型机,Meta透露元宇宙「家底」

Install mysql5.6 under linux64bit - the root password cannot be modified

Bi skill - judge 0 and null

"One good programmer is worth five ordinary programmers!"

程序员:是花光积蓄在深圳买房?还是回到长沙过“富余”生活?
随机推荐
Using macro code to generate handwriting automatically in word or WPS
Matlab rounding
Bi-sql Union
这个国庆!腾讯云WeCity陪您一同出行,点亮城市地标...
Scala IO read by line
Transform BeanUtils to achieve list data copy gracefully
对技术的乐观,正让戴尔取得比想象中更多的成就
欢迎来到联想智能大屏的新世界
15.线程同步的几种方法
Contentresolver, get the SMS content
This national day! Tencent cloud wecity will accompany you to travel and light up the city landmark
弹性蛋白酶中英文说明书
IPC机制
戴尔为何一直拒绝将商用本的超薄推向极致?
纹理增强
[practical series] full WiFi coverage at home
Fan benefits, JVM manual (including PDF)
新手看过来,带你一次性了解“软考”
Tencent moved!
Is it reliable to open an account on the flush with a mobile phone? Is there any hidden danger in this way