《算法分析与设计》Week 10

74. Search a 2D Matrix


Description:

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.


Solution:

一、题意理解

     在一个m x n 的二维矩阵中做一个查找算法。矩阵有下面的特点

     (1) 每一行从左到右是升序的。

     (2) 每一行第一个数比上一行最后一个数要大。


二、分析

     1、直接查找的方式是对每一行执行一个二分查找,时间复杂度为 O(mLog(n))

     2、仔细看一下题目中矩阵的特点,发现其完全可以当做一个一维矩阵,只需要将每一行首位连接即可,连接后的一维矩阵就是一个升序的数组,可以执行二分茶盏,时间复杂度为O(Log(mn))。这里所说的连接也不是真正的连接,只需要将一维数组的下标转化到二位矩阵的坐标即可。

     3、代码如下:

class Solution {
public:
    bool searchMatrix(vector>& matrix, int target) {
        int row = matrix.size();
        if(row == 0)
            return false;
        int column = matrix[0].size();
        if(column == 0)
            return false;
        
        int begin = 0, end = row * column - 1;
        while(begin <= end)
        {
            int index = (begin + end) / 2;
            int num = matrix[index / column][ index % column];
            if(target == num)
                return true;
            else if(target < num)
                end = index - 1;
            else
                begin = index + 1;
        }
        return false;
    }
};



你可能感兴趣的:(《算法分析与设计》)