Leetcode 240. Search a 2D Matrix II[medium]

题目:
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.


做法:分治
对于矩阵中的任何一个数x,如果target<=x,则target不会存在于x右下角的子矩阵中;若target>x,则target不会存在于x左上角的子矩阵中。
所以由T(n*m) = 3*T(n*m/4),可知该算法复杂度为O((n*m)^0.8),已经可以卡时通过这道题了。
卡时

class Solution {
public:
    bool searchMatrix(vector< vector<int> >& matrix, int target) {
        int x1 = 0, x2 = matrix.size() - 1;
        int y1 = 0, y2 = matrix[0].size() - 1;
        return dsearchMatrix(matrix, target, x1, y1, x2, y2);
    }

    bool dsearchMatrix(vector< vector<int> >& matrix, int target, int x1, int y1, int x2, int y2) {
        //cout << x1 << "  "<< x2 << "  " << y1 << "  " << y2 << endl;
        if (x1 > x2 || y1 > y2 || target < matrix[x1][y1] || target > matrix[x2][y2]) return false;
        if (x1 == x2 && y1 == y2) return target == matrix[x1][y1]; 

        int x = (x1 + x2) / 2;
        int y = (y1 + y2) / 2;

        if (target <= matrix[x][y]) return dsearchMatrix(matrix, target, x1, y1, x, y) | dsearchMatrix(matrix, target, x + 1, y1, x2, y2) | dsearchMatrix(matrix, target, x1, y + 1, x, y2);
        else return dsearchMatrix(matrix, target, x + 1, y + 1, x2, y2) | dsearchMatrix(matrix, target, x + 1, y1, x2, y2) | dsearchMatrix(matrix, target, x1, y + 1, x, y2);
    }
};

上面的方法写起来比较麻烦,更简单的是对每一行(列)通过二分法查找target。
这样的复杂度是O(nlogm),nlogn < n^1.6。

测试用时也证明了这点。
这里写图片描述

class Solution {
public:
    bool searchMatrix(vector< vector<int> >& matrix, int target) {
        for (int i = 0; i < matrix.size(); i++) {
            vector<int>::iterator it = lower_bound(matrix[i].begin(), matrix[i].end(), target);
            if (it != matrix[i].end() && *it == target) return true;
        } 
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值