lintcode刷题——搜索二维矩阵

lintcode刷题之搜索二维矩阵,题目如下所示:

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

这个矩阵具有以下特性:

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

考虑下列矩阵:

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

给出 target = 3,返回 true


做题思路:

1、由于每一个vector里面都是有序的,所以首先找到待搜索元素在哪一个vector里面;

2、找到待搜索元素所在的vector之后再对该行数据进行二分法查找;


具体的c++代码如下:

class Solution {
public:
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
     
     
    bool erfenchazhao(vector<int>&v,int target)
    {
        if(v.size()==0)
        {
            return false;
        }
        int i,j;
        i=0,j=v.size()-1;
        int temp=(i+j)/2;
        while(i<=j)
        {
            if(v[temp]<target)
            {
                i=temp+1;
                temp=(i+j)/2;
            }
            else if(v[temp]>target)
            {
                j=temp-1;
                temp=(i+j)/2;
            }
            else
            {
                return true;
            }
        }
        return false;
    }
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        // write your code here
        int row=matrix.size();
        if(row==0)
        {
            return false;
        }
        int col=matrix[0].size();
        int t;
        int i,j;
        for(i=0;i<row;i++)
        {
            if(target<matrix[i][0])
            {
                t=i;
                break;
            }
        }
        if(i==row)
        {
            return erfenchazhao(matrix[row-1],target);
        }
        if(t==0)
        {
            return false;
        }
        else
        {
              return erfenchazhao(matrix[t-1],target);
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值