leetcode - Search a 2D Matrix II
题目:
Search a 2D Matrix II
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
.
分析:
时间复杂度O(log(min(m,n)))。
for循环每次都仅仅保留矩阵的“左上角”。
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty() || matrix[0].empty()) return false; int rows=matrix.size(),cols=matrix[0].size(); int endrow=cols-1,endcol=rows-1; for(int i=0;i<=min(rows,cols)-1;++i) { int r1=checkrows(matrix,target,i,endrow); if(r1==-2)//找到了 return true; if(r1==-1)//所有都大,或者i>endrow return false; int r2=checkcols(matrix,target,i,endcol); if(r2==-2)//找到了 return true; if(r2==-1)//所有都大。或者i>endcol return false; endrow=r1; endcol=r2; } return false; } int checkrows(vector<vector<int>>& m, int target,int begin,int end) { int row=begin; int res=-1; while(begin<=end) { int mid=begin+(end-begin)/2; if(m[row][mid]==target) return -2; else if(m[row][mid]<target) { res=mid; begin=mid+1; } else end=mid-1; } return res; } int checkcols(vector<vector<int>>& m, int target,int begin,int end) { int col=begin; int res=-1; while(begin<=end) { int mid=begin+(end-begin)/2; if(m[mid][col]==target) return -2; else if(m[mid][col]<target) { res=mid; begin=mid+1; } else end=mid-1; } return res; } };