Search a 2D Matrix II
http://www.lintcode.com/en/problem/search-a-2d-matrix-ii/
Solution
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) {
int m = matrix.size();
if(m == 0) return 0;
int n = matrix[0].size();
if(n == 0) return 0;
int i = 0, j = n-1;
int cnt = 0;
while(i<m && j<n) {
if(matrix[i][j] == target) {
cnt++;
i++;
j--;
} else if(matrix[i][j] > target) {
j--;
} else {
i++;
}
}
return cnt;
}
};