240. Search a 2D Matrix II(divide and conquer)

来源:互联网 发布:数据库关系模型分析 编辑:程序博客网 时间:2024/06/05 16:26

1. 题目描述


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.


2. 算法分析

最糟糕的想法当然是暴力搜索了。但是,我们观察一下,每一行都是向右递增的,而每一列都是向下递增的,这说明已经为我们的解法“排好序”了。这样就很容易些想到结合有序表查找算法。采用分治的思想,将大问题逐步转化为小问题,更小的问题,舍去不必要的运算。从第一行开始找到第一个大于或等于target的数,如果等于那么完成搜索,如果大于,那么说明后面的全部大于(包括列对应的行的所有数),因此问题可以缩小为前面查找过的列对应行形成的子矩阵,采用递归的做法即可。


### 3. 算法设计
#include<iostream>#include<vector>using namespace std;bool searchMatrixRecursive(vector<vector<int> >&matrix, int row, int col, int target) {    for(int r = row; r < matrix.size(); r++) {        for(int c = 0; c < col; c++) {            if(matrix[r][c] > target) {                return searchMatrixRecursive(matrix, r+1, c, target);            } else if(matrix[r][c] == target) {                return true;            }         }    }    return false;}bool searchMatrix(vector<vector<int> >& matrix, int target) {     if(matrix.empty())        return false;    else        return searchMatrixRecursive(matrix, 0, matrix[0].size(), target);}int main() {    vector<vector<int> > matrix;    for(int i = 0; i < 6; i++) {        vector<int> tmp;        for(int j = 0; j < 5; j++) {            tmp.push_back((j+1)*(i+1));        }        cout << endl;        matrix.push_back(tmp);    }    int target = 8;    cout << searchMatrix(matrix, target) << endl;}

**值得注意的是,不要忘记判断矩阵为空的情况!**


4. 算法优化

Accept后发现这个算法的性能并不好,如下图所示
这里写图片描述
时间复杂度和空间复杂度都很高(待优化)

注意到使用了尾递归,改造尾递归为迭代,得到更好的性能。

bool searchMatrix(vector<vector<int> >& matrix, int target) {    if(matrix.empty()) {        return false;    }    int m = matrix[0].size()-1, n = 0;    while(n < matrix.size() && m >= 0) {        if(matrix[n][m] == target)             return true;        else if( matrix[n][m] < target)                 n++;        else                 m--;         }    return false;       }

这里写图片描述

时间上改进了700多ms,可见尾递归确实浪费时间和空间开销。