Problem Summary
Search for the value T in an M x N matrix and 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.
Solution
We can use two values i and j to mark the current position we are at. And we use the following algorithm.
- Let i = 0 and j = N-1.
- If matrix[i][0] > T , then the search is finished (Because of the property 2 of the matrix).
- While matrix[i][j] > T and j ≥ 0 , decrease j by 1.
- If j < 0 , then finish the search.
- If matrix[i][j] == T, then increase the answer by 1.
- Increase i by 1 and if i < M, go back to step 2.
Note that, because the matrix has property 2, we do not need to set j to N-1 every time we increase i.
The time complexity is O(M+N) and only constant extra space is needed.
Code
|
|