标签:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
思路:1.二分比较判断可能在哪一行,确定searchRow,再在searchRow中二分找
2. 当成线性表,来二分找。
注意:这两个的复杂度???? 1.O(lgm+lgn) 2.O(lg(m*n))
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if(matrix.empty()) return false; int row = matrix.size(); int rowA=0; int rowB = row-1; int rowMid=0; int searchRow; while(rowA<rowB){ rowMid = (rowA+rowB)/2; if(target<matrix[rowMid][0]){ if(rowMid-1<0) return false; else if(target>=matrix[rowMid-1][0]){searchRow=rowMid-1;break;} else rowB=rowMid-2; }else{ if(target<matrix[rowMid+1][0]){searchRow=rowMid;break;} else rowA=rowMid+1; } } if(rowA==rowB) searchRow = rowA; int col = matrix[0].size(); int colA=0; int colB=col-1; int colMid=0; if(target<matrix[searchRow][colA] || target>matrix[searchRow][colB]) return false; while(colA<=colB){ colMid = (colA+colB)/2; if(target==matrix[searchRow][colMid]) return true; if(target<matrix[searchRow][colMid]) colB=colMid-1; else colA=colMid+1; } return false; } };
标签:
原文地址:http://www.cnblogs.com/renrenbinbin/p/4333325.html