题目:
Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.
This matrix has the following properties:
- Integers in each row are sorted from left to right.
- Integers in each column are sorted from up to bottom.
- No duplicate integers in each row or column.
题解:
class Solution {
public:
/**
* @param matrix: A list of lists of integers
* @param target: An integer you want to search in matrix
* @return: An integer indicate the total occurrence of target in the given matrix
*/
int searchMatrix(vector<vector<int> > &matrix, int target) {
if (matrix.empty() || matrix[].empty()) {
return ;
} int cnt = ;
int m = matrix.size(), n = matrix[].size(); for (int i = , j = n - ; i < m && j >= ; ) {
if (matrix[i][j] == target) {
cnt++;
}
if (matrix[i][j] > target) {
--j;
} else {
++i;
}
} return cnt;
}
};