Description:
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.
Solution:
先二分找到所在的行,再二分找到所在的列。
import java.util.*;
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int l, r, mid;
l = 0;
r = matrix.length;
while (l + 1 < r) {
mid = (l + r) / 2;
if (matrix[mid][0] == target)
return true;
if (matrix[mid][0] > target)
r = mid;
else
l = mid;
}
int line = l;
l = 0;
r = matrix[0].length;
while (l + 1 < r) {
mid = (l + r) / 2;
if (matrix[line][mid] == target)
return true;
if (matrix[line][mid] > target)
r = mid;
else
l = mid;
}
if (matrix[line][l] == target)
return true;
return false;
}
}