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
.
编写一个有效的算法,在m × n矩阵中搜索一个值。该矩阵具有以下属性:
- 每行中的整数从左到右排序。
- 每行的第一个整数大于前一行的最后一个整数。
例如,考虑下面的矩阵:
[ [1,3,5,7], [10,11,16,20], [23,30,34,50] ]
给定目标 = 3
,返回true
。
(1)思想1:依旧使用二分法,由于是排序的数组,所以,先对数组的第一列进行二分法查询,得到位于哪一行,然后再对那一行进行二分法查询,得到最终结果,代码如下:
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 if (matrix.empty() || matrix[0].empty()) 5 return false; 6 if (target < matrix[0][0] || target > matrix.back().back()) 7 return false; 8 int begin=0; 9 int end=matrix.size()-1; 10 while(begin<=end) 11 { 12 int mid=begin+(end-begin)/2; 13 if(matrix[mid][0]==target) 14 return true; 15 else if(matrix[mid][0]<target) 16 begin=mid+1; 17 else 18 end=mid-1; 19 } 20 int temp=end; 21 begin=0; 22 end=matrix[temp].size()-1; 23 while(begin<=end) 24 { 25 int mid=begin+(end-begin)/2; 26 if(matrix[temp][mid]==target) 27 return true; 28 else if(matrix[temp][mid]<target) 29 begin=mid+1; 30 else 31 end=mid-1; 32 } 33 return false; 34 } 35 };