题目:
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.
因为排序过,思路很清晰。建立每行首元素的索引,然后行二分搜索,最后列二分搜索。复杂度是O(lg(m) + lg(n))。但是难点在于细节:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
vector<int> rowfirst;
for(int i=0; i<matrix.size(); i++) rowfirst.push_back(matrix[i][0]);
int head = 0;
int tail = matrix.size() - 1;
while(head <= tail){
if(head + 1 == tail || head == tail){
if(target == rowfirst[head] || target == rowfirst[tail]) return true;
else break;
}
int mid = (head + tail) / 2;
if(target > rowfirst[tail]) head = tail;
else if(target == rowfirst[mid] || target == rowfirst[tail]) return true;
else if(target < rowfirst[mid]) tail = mid;
else if(target > rowfirst[mid]) head = mid;
}
if(head > tail) return false;
int first = 0;
int last = matrix[0].size() - 1;
while(first <= last){
if(first == last || first + 1 == last){
if (matrix[head][first] == target || matrix[head][last] == target) return true;
else return false;
}
int mid = (first + last) / 2;
if(target == matrix[head][mid] || target == matrix[head][last]) return true;
else if(target < matrix[head][mid]) last = mid;
else if(target > matrix[head][mid]) first = mid;
}
return false;
}
};版权声明:本文为博主原创文章,转载请联系我的新浪微博 @iamironyoung
【LeetCode从零单刷】Search a 2D Matrix
原文:http://blog.csdn.net/ironyoung/article/details/49507773