[LintCode]38.搜索二维矩阵 II

xiaoxiao2021-02-28  105

写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

这个矩阵具有以下特性:每行中的整数从左到右是排序的。每一列的整数从上到下是排序的。在每一行或每一列中没有重复的整数。

样例:考虑下列矩阵:

[

    [1, 3, 5, 7],

    [2, 4, 7, 8],

    [3, 5, 9, 10]

]

给出target = 3,返回 2

思路:从左下角或右上角开始搜索均可,每次判断大小换行或者换列移动。比较matrix[row][col]与target的关系。

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) { if(matrix.empty() || matrix[0].empty()) { return 0; } int row=0; int col=matrix[0].size()-1; int count=0; while(row<matrix.size() && col>-1){ if(matrix[row][col]==target){ count++; col--; // row++; //加上这两行,避免死循环 }else if(matrix[row][col] > target){ col--; }else{ row++; } } return count; } };

转载请注明原文地址: https://www.6miu.com/read-30273.html

最新回复(0)