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
原文地址:https://www.cnblogs.com/superzrx/p/3352683.html