zoukankan      html  css  js  c++  java
  • LeetCode-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:
        int getVal(vector<vector<int> >&matrix,int i){
            int x=i/matrix[0].size();
            int y=i-x*matrix[0].size();
            return matrix[x][y];
        }
        bool searchMatrix(vector<vector<int> > &matrix, int target) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(matrix.size()==0||matrix[0].size()==0)return false;
            int start=0;
            int end=matrix.size()*matrix[0].size()-1;
            while(start<=end){
                int mid=(start+end)/2;
                int val=getVal(matrix,mid);
                if(target>val){
                    start=mid+1;
                }
                else if(target==val)
                    return true;
                else{
                    end=mid-1;
                }
            }
            return false;
        }
    };
    View Code
  • 相关阅读:
    UOJ388 [UNR #3] 配对树
    洛谷P6151 [集训队作业2019] 青春猪头少年不会梦到兔女郎学姐
    CF908H New Year and Boolean Bridges
    CF704C Black Widow
    CF1338
    CF1361
    CF1110H Modest Substrings
    CF1322
    CF1182F Maximum Sine
    Elastic Stack(ELK)
  • 原文地址:https://www.cnblogs.com/superzrx/p/3352683.html
Copyright © 2011-2022 走看看