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

88 lines
4.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [74. ](https://leetcode-cn.com/problems/search-a-2d-matrix/)\*\*\*\*
使
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?
mid/ mid = 44 /3 = 1, mid = 7 7/3=2 mid % mid = 77%3 = 1 7 2
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/二维数组.63nd4jlj0v00.png)
leetcode 74
###
####
m x n
1
> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 3
> true
2
> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 13
> false
3
> matrix = [], target = 0
> false
####
mid mid target left right
![](https://img-blog.csdnimg.cn/20210318133244216.gif)
####
Java Code:
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
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;
}
}
```