美文网首页
[Leetcode] 67. Search a 2D Matri

[Leetcode] 67. Search a 2D Matri

作者: 时光杂货店 | 来源:发表于2017-03-24 11:59 被阅读8次

    题目

    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.

    解题之法

    class Solution {
    public:
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            if (matrix.empty() || matrix[0].empty()) return false;
            if (target < matrix[0][0] || target > matrix.back().back()) return false;
            int m = matrix.size(), n = matrix[0].size();
            int left = 0, right = m * n - 1;
            while (left <= right) {
                int mid = (left + right) / 2;
                if (matrix[mid / n][mid % n] == target) return true;
                else if (matrix[mid / n][mid % n] < target) left = mid + 1;
                else right = mid - 1;
            }
            return false;
        }
    };
    

    分析

    当然这道题也可以使用一次二分查找法,如果我们按S型遍历该二维数组,可以得到一个有序的一维数组,那么我们只需要用一次二分查找法,而关键就在于坐标的转换,如何把二维坐标和一维坐标转换是关键点,把一个长度为n的一维数组转化为mn的二维数组(mn = n)后,那么原一维数组中下标为i的元素将出现在二维数组中的[i/n][i%n]的位置。

    相关文章

      网友评论

          本文标题:[Leetcode] 67. Search a 2D Matri

          本文链接:https://www.haomeiwen.com/subject/bzaxottx.html