Search a 2D Matrix II

Search a 2D Matrix II.png

解題思路 :

看到 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>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容