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, return true.
if observe carefully, it is actually using binary search..... row1, row2, row3 increasing sequentially.
#include <vector>
#include <iostream>
using namespace std;
int findMatrix(vector< vector<int> >& matrix, int pos) {
int cols = matrix[0].size();
int row = pos / cols;
int col = pos % cols;
return matrix[row][col];
}
bool searchMatrix(vector< vector<int> >& matrix, int target) {
if(matrix.size() == 0) return false;
if(matrix[0].size() == 0) return false;
int left = 0;
int right = matrix.size() * matrix[0].size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
int value = findMatrix(matrix, mid);
if(value == target) return true;
else if(value < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
} // time complexity O(lg(mn))
int main(void) {
vector< vector<int> > matrix { {0, 1, 2},{3, 4, 5}, {6, 7, 8} }; // supported by -std=c++11
bool findTarget = searchMatrix(matrix, 10);
cout << findTarget << endl;
}
本文介绍了一种在具有特定排序规则的二维矩阵中查找目标值的高效算法,利用了二分查找策略,时间复杂度为O(lg(mn))。
609

被折叠的 条评论
为什么被折叠?



