美文网首页
Search a 2D Matrix II

Search a 2D Matrix II

作者: 一枚煎餅 | 来源:发表于2016-09-15 14:54 被阅读0次
    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>

    相关文章

      网友评论

          本文标题:Search a 2D Matrix II

          本文链接:https://www.haomeiwen.com/subject/pzsbettx.html