搜索二维矩阵

本文介绍了一种在排序的二维矩阵中搜索特定值的高效算法,该算法的时间复杂度为O(log(n)+log(m)),适用于每行元素按升序排列且每行首元素大于上一行末元素的矩阵。通过两个指针分别从矩阵的左下角和右上角开始,逐步缩小搜索范围,直至找到目标值或确定不存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

28. 搜索二维矩阵

写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每行的第一个数大于上一行的最后一个整数。

样例

考虑下列矩阵:

[
  [1, 3, 5, 7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

给出 target = 3,返回 true

挑战

O(log(n) + log(m)) 时间复杂度

public class Solution {
    /**
     * @param matrix: matrix, a list of lists of integers
     * @param target: An integer
     * @return: a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if(matrix==null || matrix.length<1) 
        {
            return false;
        }
        int r=0;
        int c=matrix[0].length-1;
        while(r<matrix.length && c>=0)
        {
            if(matrix[r][c]<target)
            {
                r++;
            }else if(matrix[r][c]>target)
            {
                c--;
            }else
            {
                return true;
            }
        }
        return false;
    }
}

###########################################################

class Solution {
public:
    /**
     * @param matrix: matrix, a list of lists of integers
     * @param target: An integer
     * @return: a boolean, indicate whether matrix contains target
     */
    bool searchMatrix(vector<vector<int>> &matrix, int target) {
        // write your code here
        if(matrix.size()<1) return 0;
        int r=matrix.size();
        int c=matrix[0].size();
        int L=0;
        int R=r*c-1;
        while(L<=R)
        {
            int mid=L+((R-L)>>1);
            int midNumber=matrix[mid/c][mid%c];
            if(midNumber>target)
            {
                R=mid-1;
            }else if(midNumber<target)
            {
                L=mid+1;
            }else
            {
                return true;
            }
        }
        return false;
    }
};


#############################################################

class Solution:
    """
    @param matrix: matrix, a list of lists of integers
    @param target: An integer
    @return: a boolean, indicate whether matrix contains target
    """
    def searchMatrix(self, matrix, target):
        # write your code here
        if len(matrix)<1:
            return False
        r=len(matrix)
        c=len(matrix[0])
        L=0
        R=r*c-1
        while L<=R:
            mid=L+((R-L)>>1)
            midN=matrix[int(mid/c)][int(mid%c)]
            if midN>target:
                R=mid-1
            elif midN<target:
                L=mid+1 
            else:
                return True
        return False

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值