当前位置:网站首页>搜索二维矩阵[二分巧用 + 记录不同于插入二分的解法]
搜索二维矩阵[二分巧用 + 记录不同于插入二分的解法]
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 搜索二维矩阵
边栏推荐
- 生态护航 云服务商挥起“英特尔大旗”
- How about compass stock trading software? Is it safe?
- Cobalt Strike安装教程
- Contentresolver, get the SMS content
- Texture enhancement
- 弹性蛋白酶中英文说明书
- This national day! Tencent cloud wecity will accompany you to travel and light up the city landmark
- mysql查询时间戳转换成日期格式
- Use redis' sorted set to make weekly hot Reviews
- 丹麥技術大學首創將量子計算應用於能源系統潮流建模
猜你喜欢

Danish Technical University pioneered the application of quantum computing to power flow modeling of energy system

Cobalt strike installation tutorial

Bi-sql between

Bi SQL constraints

Première application de l'informatique quantique à la modélisation des flux de puissance dans les systèmes énergétiques à l'Université technique danoise

丹麥技術大學首創將量子計算應用於能源系統潮流建模

Assembly language (4) function transfer parameters

Bi SQL drop & alter

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?

天书夜读笔记——内存分页机制
随机推荐
JVM directive
matlab 取整
Texture enhancement
Activity lifecycle
木瓜蛋白酶中英文说明书
Bi-sql - join
Bi-sql - different join
1. package your own scaffold 2 Create code module
天书夜读笔记——深入虚函数virtual
【实用系列】家内wifi全覆盖
Merge sort template & understanding
Convolution and transpose convolution
ImageView shows network pictures
腾讯云WeCity丨你好 2022!
丹麥技術大學首創將量子計算應用於能源系統潮流建模
Q1季度逆势增长的华为笔电,正引领PC进入“智慧办公”时代
高考之后,必然会出现以下四种情况:
Install mysql5.6 under linux64bit - the root password cannot be modified
腾讯完成全面上云 打造国内最大云原生实践
Tencent cloud wecity Industry joint collaborative innovation to celebrate the New Year!