解題思路 :
看到 m+n 則考慮線性 題目發現可使用對角線的搜尋法 從右上到左下搜尋(或是左下到右上) 實際並不複雜直接讀 code 即可
C++ code :
<pre><code>
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) {
// write your code here
if(matrix.size() == 0) return 0;
int m = matrix.size(), n = matrix[0].size();
int i = 0, j = n - 1;
int count = 0;
while(i < m && j >= 0)
{
if(matrix[i][j] == target) count++;
if(matrix[i][j] > target) j--;
else i++;
}
return count;
}
};
<code><pre>