zoukankan      html  css  js  c++  java
  • 55搜索二维矩阵 II(240)

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

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

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

    问题描述 :

    编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。要求使用二分查找。

    该矩阵具有以下特性:

    每行的元素从左到右升序排列。

    每列的元素从上到下升序排列。

    说明:以上所说的升序,由于中间存在重复元素,因此严格来说,“升序”应该理解成“非递减”

    示例:

    现有矩阵 matrix 如下:

    [

      [1,   4,  7, 11, 15],

      [2,   5,  8, 12, 19],

      [3,   6,  9, 16, 22],

      [10, 13, 14, 17, 24],

      [18, 21, 23, 26, 30]

    ]

    给定 target = 5,返回 true。

    给定 target = 20,返回 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.size()==0||matrix[0].size()==0)
                return false;
            int m=matrix.size()-1,n=0;
            //从左下角的元素开始判断,因为他一定是列的最小,行的最大 
            while(m>=0&&n<matrix[0].size())
            {
                if(target==matrix[m][n]) 
                    return true;
                else if(target<matrix[m][n])//目标值小于左下角的值,行数上移 
                    m--;
                else
                    n++;//否则,列数右移 
            }
            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;
    }
  • 相关阅读:
    EBS SQL > Form & Report
    oracle sql 优化分析点
    MRP 物料需求计划
    MRPII 制造资源计划
    Barcode128 应用实务
    Oracle SQL语句优化技术分析
    APPSQLAP10710 Online accounting could not be created. AP Invoice 无法创建会计分录
    Oracle数据完整性和锁机制
    ORACLE Responsibility Menu Reference to Other User
    EBS 常用 SQL
  • 原文地址:https://www.cnblogs.com/zmmm/p/13635891.html
Copyright © 2011-2022 走看看