zoukankan      html  css  js  c++  java
  • 51搜索二维矩阵(74)

    作者: Turbo时间限制: 1S章节: 二分查找

    晚于: 2020-08-12 12:00:00后提交分数乘系数50%

    截止日期: 2020-08-19 12:00:00

    问题描述 :

    编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。要求使用二分查找。

    该矩阵具有如下特性:

    每行中的整数从左到右按升序排列。

    每行的第一个整数大于前一行的最后一个整数。

    示例 1:

    输入:

    matrix = [

      [1,   3,  5,  7],

      [10, 11, 16, 20],

      [23, 30, 34, 50]

    ]

    target = 3

    输出: true

    示例 2:

    输入:

    matrix = [

      [1,   3,  5,  7],

      [10, 11, 16, 20],

      [23, 30, 34, 50]

    ]

    target = 13

    输出: false

    可使用以下main函数:

    int main()

    {

        vector<vector<int> > matrix;

        int target;

        int m,n,e;

        cin>>m;

        cin>>n;

        for(int i=0; i<m; i++)

        {

            vector<int> aRow;

            for(int j=0; j<n; j++)

            {

                cin>>e;

                aRow.push_back(e);

            }

            matrix.push_back(aRow);

        }

        cin>>target;

        bool res=Solution().searchMatrix(matrix,target);

        cout<<(res?"true":"false")<<endl;

        return 0;

    }

    输入说明 :

    首先输入matrix的行数m、列数n,

    然后输入m行,每行n个整数。

    最后输入一个整数target。

    输出说明 :

    输出true或false

    输入范例 :

    输出范例 :

    #include <iostream>
    #include <vector>
    using namespace std;
    
    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) 
        {
            if(matrix.empty())
                return false;
            int l=0;
            int r=matrix.size()*matrix[0].size()-1;
            int len=matrix[0].size();
            while(l<=r)
            {
                int mid=(l+r)/2;
                if(matrix[mid/len][mid%len]>target)
                    r=mid-1;
                else if(matrix[mid/len][mid%len]<target)
                    l=mid+1;
                else
                    return true;
            }
        return false;
        }
    };
    
    int main()
    {
        vector<vector<int> > matrix;
        int target;
        int m,n,e;
        cin>>m;
        cin>>n;
        for(int i=0; i<m; i++)
        {
            vector<int> aRow;
            for(int j=0; j<n; j++)
            {
                cin>>e;
                aRow.push_back(e);
            }
            matrix.push_back(aRow);
        }
        cin>>target;
        bool res=Solution().searchMatrix(matrix,target);
        cout<<(res?"true":"false")<<endl;
        return 0;
    }

    其实就是一个升序序列,用二分法来做,只不过判断中间节点时要以二维数组的方法来判断。

  • 相关阅读:
    Halcon各个算子角度计算方式汇总
    阈值分割算子之OSTU算法
    Halcon18--深度学习应用问题记录
    Halcon18新技术
    Halcon之3D重建
    关于数组排序(顺序,逆序)
    封装jq的ajax
    h5在微信生成分享海报(带二维码)
    使用mintUI的总结
    时间戳转日期
  • 原文地址:https://www.cnblogs.com/zmmm/p/13635089.html
Copyright © 2011-2022 走看看