题目:
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
.
题意:给出一个m*n的二维矩阵,具有以下特点:
(1)每一行按照升序排序
(2)每一列按照升序排列
现给出一个值,求该值是否在二维矩阵中存在。这里直接二次循环查找时间复杂度为o(m*n),肯定会超时的。所以我先查找可能出现target的列和行,然后对可能的行和列分别做二分查找。
代码:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length==0||matrix[0].length==0) //空矩阵返回false return false; int row=matrix.length; int col=matrix[0].length; int mayRow=-1; //可能的行 int mayCol=-1; //可能的列 for(int i=0;i<row;i++){ //寻找可能出现target的行 if(matrix[i][0]<=target&&matrix[i][col-1]>=target){ mayRow=i; int low=0; int high=col-1; while(low<=high){ int mid=(low+high)/2; if(matrix[mayRow][mid]==target){ System.out.println("true"); return true; }else if(matrix[mayRow][mid]>target){ high=mid-1; }else if(matrix[mayRow][mid]<target){ low=mid+1; } } } } for(int i=0;i<col;i++){ //寻找可能出现target的列 if(matrix[0][i]<=target&&matrix[row-1][i]>=target){ mayCol=i; int low=0; int high=row-1; while(low<=high){ int mid=(low+high)/2; if(matrix[mid][mayCol]==target){ System.out.println("true"); return true; }else if(matrix[mid][mayCol]>target){ high=mid-1; }else if(matrix[mid][mayCol]<target){ low=mid+1; } } } } System.out.println("false"); return false; } }