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;
        }
    };
  • 相关阅读:
    Tomcat启动startup.bat闪退和JRE_HOME错误
    页面布局:一侧固定宽度,一侧自适应
    iOS-数据持久化-CoreData
    iOS-数据持久化-SQlite3
    iOS-数据持久化-偏好设置
    iOS-数据持久化-对象归档
    iOS-数据持久化-属性列表
    iOS-数据持久化基础-沙盒机制
    iOS-数据持久化详细介绍
    iOS-网络处理框架AFN
  • 原文地址:https://www.cnblogs.com/hrnn/p/13415701.html
Copyright © 2011-2022 走看看