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;
        }
    */
    };
  • 相关阅读:
    第二次冲刺阶段第四天
    第二次冲刺阶段第三天
    第二次冲刺阶段第二天
    人月神话阅读笔记03
    第二次冲刺阶段第一天
    学习进度条(十二)
    课堂练习-找水王
    学习进度条(十一)
    学习进度表第十周
    构建之法阅读笔记06
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281469.html
Copyright © 2011-2022 走看看