algorithm-base/animation-simulation/二分查找及其变种/二维数组的二分查找.md

88 lines
4.5 KiB
Java
Raw Normal View History

2021-07-23 15:44:19 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
2021-03-20 09:16:07 +00:00
>
>
>
2021-07-23 15:44:19 +00:00
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 09:16:07 +00:00
2021-07-23 15:44:19 +00:00
#### [74. ](https://leetcode-cn.com/problems/search-a-2d-matrix/)\*\*\*\*
2021-03-18 05:33:53 +00:00
使
2021-07-23 15:44:19 +00:00
7使 9 left = 0right = 9 - 1= 8 mid mid = left +(right - left) >> 1 mid = 4 nums[2,2] 4 mid = 4 3 3 mid =4?
2021-03-18 05:33:53 +00:00
2021-07-23 15:44:19 +00:00
mid/ mid = 44 /3 = 1, mid = 7 7/3=2 mid % mid = 77%3 = 1 7 2
2021-03-18 05:33:53 +00:00
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/二维数组.63nd4jlj0v00.png)
2021-07-23 15:44:19 +00:00
leetcode 74
2021-03-18 05:33:53 +00:00
###
####
m x n
2021-07-23 15:44:19 +00:00
1
2021-03-18 05:33:53 +00:00
> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 3
> true
2021-07-23 15:44:19 +00:00
2
2021-03-18 05:33:53 +00:00
> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 13
> false
2021-07-23 15:44:19 +00:00
3
2021-03-18 05:33:53 +00:00
> matrix = [], target = 0
> false
####
2021-07-23 15:44:19 +00:00
mid mid target left right
2021-03-18 05:33:53 +00:00
![](https://img-blog.csdnimg.cn/20210318133244216.gif)
####
Java Code:
2021-03-18 05:33:53 +00:00
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
2021-07-23 15:44:19 +00:00
2021-03-18 05:33:53 +00:00
if (matrix.length == 0) {
return false;
}
//行数
int row = matrix.length;
//列数
int col = matrix[0].length;
int left = 0;
//行数乘列数 - 1右指针
int right = row * col - 1;
while (left <= right) {
int mid = left+ ((right-left) >> 1);
//将一维坐标变为二维坐标
int rownum = mid / col;
int colnum = mid % col;
if (matrix[rownum][colnum] == target) {
return true;
} else if (matrix[rownum][colnum] > target) {
right = mid - 1;
} else if (matrix[rownum][colnum] < target) {
left = mid + 1;
}
}
return false;
}
}
```