Search a 2D Matrix
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
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
, return true
.
Challenge
O(log(n) + log(m)) time
SOLUTION:
这题看到排序数组,就有可能用二分法,然后看到challenge是logn + logm的,就肯定是二分了,第一眼看上去是应该两个二分,找到在哪一行,再在这一行里找,但是,仔细看题目,这个matrix是绝对递增的,就是第二行第一个数绝对大于迪一行最后一个数,也就是说,把每一行都摆在一起,就是一个连续的排列的递增的数组。。。这就好办了,一个binary search就解决了。
然后就是怎么把matrix表示成一行,怎么表示end。
end 可以等于 (行数*列数 -1),然后对应的A[mid] = matrix[mid/行数] [mid%行数] : 第一个行数,就是直接用除法,看有几个行就是在第几行;然后mid去%一下,就是看它在这一行的什么位置。
最后看代码:
public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0){ return false; } if (matrix[0] == null || matrix[0].length == 0){ return false; } int row = matrix.length; int column = matrix[0].length; int start = 0; int end = matrix.length * matrix[0].length - 1; while (start + 1 < end){ int mid = start + (end - start) / 2; if (matrix[mid / column][mid % column] == target){ return true; } if (matrix[mid / column][mid % column] > target){ end = mid; } if (matrix[mid / column][mid % column] < target){ start = mid; } } if (matrix[start / column][start % column] == target){ return true; } if (matrix[end / column][end % column] == target){ return true; } return false; } }
时间: 2024-12-27 14:30:07