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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false
难度:medium
题目:设计高效算法在矩阵中搜索给定的值。矩阵特性如下:每行元素从左到右递增,每列元素从上到下递增。
思路:在第一个行中找出首元素大于target的列,在第一个列中找出首元素大于target的行。然后对每行进行二叉搜索。
Runtime: 6 ms, faster than 97.21% of Java online submissions for Search a 2D Matrix II.
Memory Usage: 46.6 MB, less than 23.14% of Java online submissions for Search a 2D Matrix II.
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int m = matrix.length, n = matrix[0].length;
int row = 0, column = 0;
for (; column < n; column++) {
if (matrix[0][column] > target) {
break;
}
}
for (; row < m; row++) {
if (matrix[row][0] > target) {
break;
}
}
for (int i = 0; i < row; i++) {
if (Arrays.binarySearch(matrix[i], 0, column, target) >= 0) {
return true;
}
}
return false;
}
}