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;
    }
  • 相关阅读:
    scala之伴生对象的继承
    scala之伴生对象说明
    “Failed to install the following Android SDK packages as some licences have not been accepted” 错误
    PATH 环境变量重复问题解决
    Ubuntu 18.04 配置java环境
    JDBC的基本使用2
    DCL的基本语法(授权)
    ZJNU 1374
    ZJNU 2184
    ZJNU 1334
  • 原文地址:https://www.cnblogs.com/zmmm/p/13635891.html
Copyright © 2011-2022 走看看