标签:
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
.
1 class Solution { 2 public: 3 4 /*解题报告 5 *这个题可以用二分查找,但是条件比较多,要依次考虑 6 *如果行数为0,则矩阵不存在, 列数为0,可以为一维数组matrix[0][i] 7 *考虑要查找的数是否在矩阵范围内,如果小于第一个数,不存在,大于最后一个数,不存在 8 *考虑只有一个数的矩阵 9 *判断行数是否为1,如果行数为1,则只需要考虑第一行,并不用计算第一列 10 * 11 */ 12 bool searchMatrix(vector<vector<int>>& matrix, int target) { 13 int row = matrix.size(); 14 15 if(row == 0) 16 return false; 17 18 int column = matrix[0].size(); 19 if(matrix[0][0] > target || matrix[row-1][column-1] < target) 20 return false; 21 22 if(matrix[0][0] == target) 23 return true; 24 25 int l = 0; 26 //高位是行数减一 27 int h = row - 1; 28 int res = 0; 29 if(row > 1){ 30 while(l <= h){ 31 int middle = (l+h)/2; 32 if(target < matrix[middle][0]) 33 h = middle - 1; 34 else if(matrix[middle][0] < target) 35 l = middle + 1; 36 else 37 return true; 38 } 39 //找到target会存在的的行数 40 res = h; 41 } 42 43 l = 0; 44 h = column-1; 45 while(l<=h){ 46 int middle = (l+h)/2; 47 if(matrix[res][middle] < target) 48 l = middle + 1; 49 else if(matrix[res][middle] > target) 50 h = middle - 1; 51 else 52 return true; 53 } 54 return false; 55 } 56 };
标签:
原文地址:http://www.cnblogs.com/horizonice/p/4770555.html