lintcode刷题——搜索二维矩阵

来源:互联网 发布:怎样做网络推广话术 编辑:程序博客网 时间:2024/06/09 19:28

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);
        }
    }
};

原创粉丝点击