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.For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]Given target =
3
, returntrue
.answer:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if(m == 0) return false; int n = matrix[0].size(); if(n == 0) return false; int mLeft = 0, mRight = m - 1, nLeft = 0, nRight = n - 1; int mMid = 0, nMid = 0; while(mLeft <= mRight){ mMid = (mLeft + mRight) / 2; nMid = (nLeft + nRight) / 2; if(matrix[mMid][nMid] > target){ if(matrix[mMid][0] > target) mRight = mMid - 1; else if(matrix[mMid][0] < target) break; else return true; } else if(matrix[mMid][nMid] < target){ if(matrix[mMid][n - 1] > target) break; else if(matrix[mMid][n - 1] < target) mLeft = mMid + 1; else return true; } else return true; } if(mLeft > mRight) return false; while(nLeft <= nRight){ nMid = (nLeft + nRight) / 2; if(matrix[mMid][nMid] < target) nLeft = nMid + 1; else if(matrix[mMid][nMid] > target) nRight = nMid - 1; else return true; } return false; }};
新闻热点
疑难解答