zoukankan      html  css  js  c++  java
  • leetcode75:search-a-2d-matrix

    题目描述

    请写出一个高效的在m*n矩阵中判断目标值是否存在的算法,矩阵具有如下特征:
    每一行的数字都从左到右排序
    每一行的第一个数字都比上一行最后一个数字大
    例如:
    对于下面的矩阵:
    [
        [1,   3,  5,  7],
        [10, 11, 16, 20],
        [23, 30, 34, 50]
    ]
    要搜索的目标值为3,返回true;

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
    • Integers in each row are sorted from left to right.
    • The first integer of each row is greater than the last integer of the previous row.


    For example,

    Consider the following matrix:

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

    Given target =3, returntrue.


    示例1

    输入

    复制
    [[1,1]],0

    输出

    复制
    false
    

    class Solution {
    public:
        /**
         *
         * @param matrix int整型vector<vector<>>
         * @param target int整型
         * @return bool布尔型
         */
        bool searchMatrix(vector<vector<int> >& matrix, int target) {
            // write code here
            int rows=matrix.size();
            int cols=matrix[0].size();
            int begin=0,end=rows*cols-1;
            
            while (begin <= end)
            {
                int mid=(begin+end)/2;
                int row=mid/cols;
                int col=mid%cols;
                if (matrix[row][col] ==target)
                    return true;
                else if (matrix[row][col]<target)
                    begin=mid+1;
                else
                    end=mid-1;
                
            }
            return false;
        }
    };
  • 相关阅读:
    obs问题记录
    树莓派数字识别相关资料
    Focus Event
    跨浏览器的事件对象
    浅谈Javascript事件模拟
    浅谈Javascript鼠标和滚轮事件
    UI Events
    IE事件对象(The Internet Explorer Event Object)
    eclipse 调试nodejs 发生Failed to connect to standalone V8 VM错误的解决方案
    关于couldn't connect to server 127.0.0.1 shell/mongo.js:84 exception: connect failed 问题
  • 原文地址:https://www.cnblogs.com/hrnn/p/13415701.html
Copyright © 2011-2022 走看看