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.

思路:这道题就是在这个二维矩阵中查找一目标值。根据这个矩阵的特点:1.每一行的值都是从小到大排列的;2.当前行的第一个元素大于上一行最后元素。根据这两个性质,我们从每一行的最后一个元素查找,如果target正好等于这个值,则返回true;如果小于这个元素,这向前移动;如果大于这个元素,则向下移动;

class Solution {

public:

    bool searchMatrix(vector<vector<int> > &matrix, int target) {

        int n=matrix.size();

        int m=matrix[0].size();

        if(n==0||m==0)

            return false;

        int i=0,j=m-1;

        while(i<n && j>=0)

        {

            if(target==matrix[i][j])

                return true;

            else if(target<matrix[i][j])

                j--;

            else

                i++;

        }

        return false;

    }

};

  

 

 

你可能感兴趣的:(search)