Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
给定一个mXn的矩阵,这个矩阵的每一行从左到右升序排序,每行的第一个值都比上一行的最后一个值大
二维矩阵可以通过坐标的运算转化为一维数组,根据题意,这个二维矩阵等价于一个有序的数组
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int rows=matrix.size(); if(rows==0)return false; int cols=matrix[0].size(); if(cols==0)return false; int low=0, high=rows*cols-1; while(low<=high){ int mid=(low+high)/2; if(matrix[mid/cols][mid%cols]==target)return true; else if(target < matrix[mid/cols][mid%cols]) high=mid-1; else low=mid+1; } return false; } };
LeetCode: Search a 2D Matrix [074],布布扣,bubuko.com
LeetCode: Search a 2D Matrix [074]
原文:http://blog.csdn.net/harryhuang1990/article/details/27354857