题目描述:(链接)
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 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 int first = 0; 5 int last = matrix.size() - 1; 6 int len = matrix[0].size(); 7 while (first <= last) { 8 int mid = first + (last - first) / 2; 9 if (matrix[mid][0] <= target && target <= matrix[mid][len - 1] ) { 10 return binarySearch(matrix[mid], target); 11 } else if (matrix[mid][0] > target) { 12 last = mid - 1; 13 } else if (matrix[mid][len - 1] < target) { 14 first = mid + 1; 15 } 16 } 17 18 return false; 19 } 20 21 private: 22 bool binarySearch(vector<int>& vec, int target) { 23 int first = 0; 24 int last = vec.size() - 1; 25 while (first <= last) { 26 int mid= first + (last -first) / 2; 27 if (vec[mid] == target) { 28 return true; 29 } else if (vec[mid] < target) { 30 first = mid + 1; 31 } else { 32 last = mid - 1; 33 } 34 } 35 36 return false; 37 } 38 };