240.Search a 2D Matrix II

来源:互联网 发布:有招聘在家淘宝客服吗 编辑:程序博客网 时间:2024/05/29 14:12

题目描述:

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.
从给定的条件发现,从矩阵中任取一个子矩阵,右下角的数为最大值。所以从第一行最右端开始比较,设行数i,列数j如果matrix[i][j]小于目标数,i+1.如果大于,则j-1,遇到边界则该数不存在。

代码如下

bool searchMatrix(vector<vector<int>>& matrix, int target){if(matrix.size()==0||matrix[0].size()==0)return false;int i=0,j=matrix[0].size()-1;while(i<matrix.size()&&j>=0){if(matrix[i][j]==target)return true;else if(matrix[i][j]<target)i++;elsej--;}return false;} 


0 0
原创粉丝点击