搜索二维矩阵

本文介绍了一个高效的算法,用于搜索一个具有特殊性质的二维矩阵中的特定值。该算法首先通过二分查找确定目标值可能所在的列,然后在该列中再次使用二分查找确定目标值是否存在。

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

搜索二维矩阵

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

这个矩阵具有以下特性:

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


class Solution {

public:
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
     int searchcol(vector<vector<int> > &matrix,int target,int m){
         int col=-1;
         int first,last;
         int mid;
         first=0;
         last=m-1;
         while(first<=last){
             mid=(first+last)/2;
             if(matrix[mid][0]>target){
                last=mid-1;
             }
             if(matrix[mid][0]<=target){
                first=mid+1; 
             }
         }
    
         return col=last;
     }
          bool searchrow(vector<vector<int> > &matrix,int target,int n,int col){
         int row;
         int first,last;
         int mid;
         first=0;
         last=n-1;
         while(first<=last){
             mid=(first+last)/2;
       //      cout<<mid<<endl;
             if(matrix[col][mid]>target){
                last=mid-1;
             }
            else if(matrix[col][mid]<target){
                
                first=mid+1;
             }
             else if(matrix[col][mid]==target)
             return true;
         }
         
         return false;
     }
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        // write your code here 
        if(matrix.empty()==true)
        return false;
        int m,n;
        int col;
        m=matrix.size();
        n=matrix[0].size();
  //     cout<<m<<" "<<n<<endl;
         col=searchcol(matrix,target,m);
     //    cout<<col<<endl;
        if(col==-1||matrix[col][0]>target)
        return false;
        else
        return searchrow(matrix,target,n,col);
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值