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.
For 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
.
一般能想到两种解法。
naive版本没有考虑到数组的性质所以就不考虑了。
第一种是对每一层进行二分法;时间复杂度O(m logn), 可以对列比较少的时候使用
第二种是从第一行的最后一列开始往左或者往下走。比当前元素小,那么col--,比当前元素大那么row++;直至找到结果。 时间复杂度是O(m+n)
对应的实现:
public class Solution {
// public boolean searchMatrix(int[][] matrix, int target) {
// if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
// for(int i=0;i<matrix.length;i++){
// if(target>= matrix[i][0]){
// boolean temp = binarySearch(matrix[i], target);
// if(temp){
// return true;
// }
// }
// }
// return false;
// }
// public boolean binarySearch(int[] array, int target){
// int low = 0;
// int high = array.length - 1;
// while(low <= high){
// int mid = low + (high - low) / 2;
// if(array[mid] == target){
// return true;
// }else if(array[mid]<target){
// low = mid +1;
// }else{
// high = mid -1;
// }
// }
// return false;
// }
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int row = 0;
int col = matrix[0].length-1;
while(row<matrix.length && col< matrix[0].length && row>=0 && col >= 0){
int value = matrix[row][col];
if(target == value){
return true;
}
if(target > value){
row++;
}
if(target < value){
col--;
}
}
return false;
}
}