74. Search a 2D Matrix
程序员文章站
2022-03-08 11:35:27
...
题目叙述:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
题目分析:
- 对一个二维矩阵进行使用二分查找,先将其计算所有元素的总数,以拉平。
- 对一个扁平结构索引编号进行除以列数可以得到该扁平索引对应的二维矩阵的行号,对列数进行取余可以得到对应的列号
- 该矩阵从左到右从上到下是依次递增的
代码:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
//对一个二维矩阵进行使用二分查找,先将其计算所有元素的总数,以拉平。
//对一个扁平结构索引编号进行除以列数可以得到该扁平索引对应的二维矩阵的行号,对列数进行取余可以得到对应的列号
//该矩阵从左到右从上到下是依次递增的
int m = matrix.length;
if(m==0) return false;
int n = matrix[0].length;
int len = m *n;
int left = 0;
int right = len-1;
while(left<=right){
int mid = left + (right-left)/2;
int value = matrix[mid/n][mid%n];
if(value == target) return true;
else if(value < target) left = mid+1;
else right = mid-1;
}
return false;
}
}
上一篇: php如何连接数据库的方法
推荐阅读
-
LeetCode 74. Search a 2D Matrix
-
74. Search a 2D Matrix
-
74. Search a 2D Matrix
-
LeetCode 74. Search a 2D Matrix
-
[leetcode]74. Search a 2D Matrix
-
leetcode -- 74. Search a 2D Matrix
-
LeetCode 74. Search a 2D Matrix
-
[leetcode] 74. Search a 2D Matrix @ python
-
[leetcode]74. Search a 2D Matrix
-
74. Search a 2D Matrix