题目描述:
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.
举例:
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
, return true
.
时间复杂度:
O(log(n) + log(m))
Code:
1 bool searchMatrix(vector<vector<int> > &matrix, int target) { 2 if(matrix.empty()) return false; //矩阵为空时 3 long long n = matrix[0].size(); //列 4 long long m = matrix.size(); //行 5 long long first = 0; //0行,0列 6 long long last = m-1; //m-1行,0列 7 long long mid; 8 while(last - first >= 0){ //第1次二分,找出元素所在的行 9 mid = first + ((last - first + 1)>>1); 10 if(matrix[mid][0] == target) return true; 11 else if(matrix[mid][0] < target){ 12 first = mid + 1; 13 }else if(matrix[mid][0] > target){ 14 last = mid - 1; 15 } 16 } 17 long long mid2; 18 if(matrix[mid][0] < target){ //第2次二分,找出元素的具体位置 19 first = 1; 20 last = n -1; 21 while(first <= last){ 22 mid2 = first + ((last - first + 1)>>1); 23 if(matrix[mid][mid2] == target) return true; 24 else if(matrix[mid][mid2] > target) last = mid2 - 1; 25 else first = mid2 + 1; 26 } 27 }else if(mid >= 1 && matrix[mid][0] > target){ 28 last = n - 1; 29 first = 0; 30 while(first <= last){ 31 mid2 = first + ((last - first + 1)>>1); 32 if(matrix[mid-1][mid2] == target) return true; 33 else if(matrix[mid-1][mid2] > target) last = mid2 - 1; 34 else first = mid2 + 1; 35 } 36 }else 37 return false; 38 39 return false; 40 }
时间: 2024-11-05 06:42:50