在排好序(或者部分排好序)的矩阵上进行搜索是考察多维数组操作和查找的一种经典面试题类型。这里假设行数和列数分别是M和N。下面根据难度来总结一下几个不同的题目变体:
1. LeetCode原题 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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
思路1:首先二分搜索确定行号,然后再二分搜索确定列号。
public boolean Find(int[][] matrix, int elem) {
// binary search the row number
int low, high, mid = 0;
low = 0;
high = matrix.length - 1;
while (low <= high) {
mid = low + (high - low) / 2;
if (matrix[mid][0] == elem) {
return true;
} else if (matrix[mid][0] > elem) {
high = mid - 1;
} else {
low = mid + 1;
}
}
// make sure the row starts with a