LeetCode OJ 240. Search a 2D Matrix II

本文介绍了解决LeetCode 240题目的两种方法:二分查找法和分治法。二分查找法适用于每一行进行搜索,总时间复杂度为O(nlogn)。而分治法利用矩阵特性,从右上角开始缩小搜索范围,时间复杂度为O(n)。

LeetCode OJ 240. Search a 2D Matrix II


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 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.

每一行采用二分查找(Binary Search)的方法。对于nxn的矩阵来说,每一行时间复杂度为O(logn),一共n行,总时间复杂度是O(nlogn)

代码


class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size(), n = matrix[0].size();
        if(m == 0 || n == 0)    return false;

            int low, high, mid;
            for(int i = 0; i < m; i++){
                low = 0; high = n - 1;
                while(low <= high){
                    mid = low + (high - low) / 2;
                    if(target == matrix[i][mid])
                        return true;
                    else if(target > matrix[i][mid])
                        low = mid + 1;
                    else
                        high = mid - 1;
                }
            }
        return false;
    }
};

方法二:Divide and Conquer

因为矩阵中的数每一行每一列都是非递减序列,所以,我们可以采用分治的思想,从右上角开始,每次去除一行或者一列,不断缩小范围。eg.
题目给出的例子矩阵,

[
[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]
]

假设我们查找的数为8,那么从右上角15判断起,8小于15和11,每一行每一列都是非递减序列,所以肯定不在这两列。此时,我们查找范围变成:

[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[10, 13, 14],
[18, 21, 23]
]

又8大于7,所以8不在7所在的行,此时,范围变为:

[
[2, 5, 8],
[3, 6, 9],
[10, 13, 14],
[18, 21, 23]
]

右上角是8,则返回true
如果查找的下标i,j超出了矩阵范围,则表示不存在这个数,返回false
算法最坏的情况是从矩阵右上角每次向左或向下遍历一个元素,最后到左下角,因此算法时间复杂度为O(n)。

代码

个人github代码链接


class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size(), n = matrix[0].size();
        if(m == 0 || n == 0)    return false;

        int i = 0, j = n - 1;
        while(i < m && j >= 0){
            if(target == matrix[i][j])
                return true;
            else if(target > matrix[i][j])
                i ++;
            else 
                j --;
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值