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;
        }
    */
    };
  • 相关阅读:
    Go语言string,int,int64 ,float转换
    Go 时间相关
    静态顺序表操作
    汇编基础
    C语言字节对齐
    BugkuCTF-游戏过关
    数组越界问题分析
    选择排序(Java)
    杨辉三角(C语言)
    二分查找(Java)
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281469.html
Copyright © 2011-2022 走看看