算法设计第三周 (分治算法)

来源:互联网 发布:人工智能计算器ios 编辑:程序博客网 时间:2024/06/01 11:23

算法题目 :Search a 2D Matrix II

算法题目描述: 

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.

算法分析:

这道题目很好理解,就是给定一个矩阵,从左到右,从上到下都已经按照从小到大的顺序排列好了,现在要设计一个算法让你从中找出一个给定 的target,一般的方法就是暴力找啊,但是这样显得很麻烦,浪费时间,时间复杂度是O(m*n),这就很大了。我们应该用到题目中给出的排好序这个特点,就是说给定一个数,在同一行要是比一个大,那么肯定比后面的都要大。同理,在同一列,要是比一个数小,肯定比这列的下面的数都小,这样我们就可以用这个特点来寻找了。这样,算法复杂度就是O(m+n),显然比O(mn)要小多了。说是分治,好像也没有用到什么分治的思想,就是用到了题目中给到的特点,真不知道这道题是要考什么。


算法代码(C++):

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        if(matrix.size() == 0)        return false;        int m = matrix.size();        int n = matrix[0].size();        int i = 0, j = n - 1;        for(; i < m && j>= 0; )                {            if(target == matrix[i][j])            return true;                        else if(target > matrix[i][j])            i++;                        else             j--;        }                return false;    }};


0 0