在二维有序数组中搜索某个数(存在否、出现次数)

在二维有序数组中搜索某个数(存在否、出现次数)

问题描述

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

这个矩阵具有以下特性:

每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。

样例
考虑下列矩阵:

[

[1, 3, 5, 7],

[2, 4, 7, 8],

[3, 5, 9, 10]

]

给出target = 3,返回 2

实现思路

由于数组每行从左到右是有序的,每列从上到下是有序的,因此可以考虑从二维数组的右上角开始搜索。首先判断右上角元素与查找目标的关系,如果目标小于右上角的元素,则不用搜索最后一列;如果目标大于右上角元素,则不用搜索第一行。
搜索路径如下图所示:
enter description here
如果题目问的是目标值是否存在时,当搜索到第一个目标值时,搜索函数就可以返回真了,如果题目问的是出现次数,则还要继续搜索下去。

 

代码实现

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 cols = matrix[0].size();
        int rows = matrix.size();
        int count = 0;
        
        int row = 0;
        int col = cols-1;
        while (row<rows && col>= 0 )
        {
            if (matrix[row][col] == target)
            {
                count++;
                row++;
            }
            else if (matrix[row][col] < target)
            {
                row++;
            }
            else
                col--;
        }

        return count;
    }
};
转载请注明出处:http://www.cnblogs.com/scut-linmaojiang/p/5146435.html 
原文地址:https://www.cnblogs.com/scut-linmaojiang/p/5146435.html