Search a 2D Matrix ——LeetCode

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.

For example,

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target = 3, return true.

题目大意:给一个m*n矩阵,每一行都是递增有序,逐行也是递增的,要求设计一个高效算法检查目标元素是否存在于此矩阵中。

解题思路:可以把整个矩阵展开,就是一个长数组,数组长度为M*N,用二分查找即可,就是需要把二分查找的位置转化为矩阵下标。假设有row行,col列,那么key对应的矩阵中的元素应该是matrix[key/col][key%col],这样就转为二分查找了。

Talk is cheap>>

   public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix[0][0] > target)
return false;
int rowLen = matrix.length;
int colLen = matrix[0].length;
int low = 0, high = rowLen * colLen - 1; while (low <= high) {
int mid = (low + high) >>> 1;
int x = mid / colLen;
int y = mid % colLen;
if (matrix[x][y] > target) {
high = mid - 1;
} else if (matrix[x][y] < target) {
low = mid + 1;
} else {
return true;
}
}
return false;
}
上一篇:python3入门之字符串


下一篇:nopcommerce商城系统--技术与系统需求