zoukankan      html  css  js  c++  java
  • leetcode[74]Search a 2D Matrix

    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, return true.

    class Solution {
    public:
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            if(matrix.empty())return false;
            int row=matrix.size();
            if(matrix[0].empty())return false;
            int col=matrix[0].size();
            int left=0,right=row*col-1;
            while(left<=right)
            {
                int mid=(left+right)/2;
                int temp=matrix[mid/col][mid%col];
                if(temp==target)return true;
                else if(temp<target)left=mid+1;
                else right=mid-1;
            }
            return false;
        }
    /**
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            if(matrix.empty())return false;
            int row=matrix.size();
            if(matrix[0].empty())return false;
            int col=matrix[0].size();
            int i=0,j=col-1;
            while(i<row&&j>=0)
            {
                if(matrix[i][j]==target)return true;
                else if(matrix[i][j]<target)i++;
                else j--;
            }
            return false;
        }
    */
    };
  • 相关阅读:
    I.MX6 Surfaceflinger 机制
    理解 Android Fragment
    RPi 2B DDNS 动态域名
    RPi 2B IPC webcam server
    理解 Android MVP 开发模式
    I.MX6 system.img unpack repack
    can't set android permissions
    VMware Ubuntu 共享文件夹
    解决oracle数据库连接不上的问题
    perfect-scrollbar示例
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281469.html
Copyright © 2011-2022 走看看