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.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
class Solution {
public:
bool searchMatrix(vector<vector<int>>& a, int target) {
int m = a.size();
if (m==0) return false;
int n = a[0].size();
if (n==0) return false;
//get target in which col
int lo = 0;
int hi = m;
while(lo<=hi) {
int mid = lo + (hi - lo) / 2;
if (mid>=m) break;
if (target < a[mid][0]) {
hi = mid - 1;
} else if (a[mid][0] < target) {
lo = mid + 1;
} else {
return true;
}
}
std::cout << lo <<std::endl;
int col = lo-1;
if (col<0 ||col>m) return false;
//get target in col
lo = 0;
hi = n;
while(lo<=hi) {
int mid = lo + (hi - lo) / 2;
if (mid>=n) break;
if (target < a[col][mid]) {
hi = mid - 1;
} else if (a[col][mid] < target) {
lo = mid + 1;
} else {
return true;
}
}
return false;
}
};
class Solution {
public boolean searchMatrix(int[][] a, int target) {
if (a.length<1)
return false;
int i = 0;
int j = a[0].length-1;
while(i<a.length && j>=0){
if(target==a[i][j])
return true;
else if(target>a[i][j])
i++;
else
j--;
}
return false;
}
}