程序员面试的那些小事数据结构和算法分析程序员

lintcode 搜索二维矩阵

2016-12-23  本文已影响202人  yzawyx0220

写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
这个矩阵具有以下特性:
每行中的整数从左到右是排序的。
每一列的整数从上到下是排序的。
在每一行或每一列中没有重复的整数。
考虑下列矩阵:

[1, 3, 5, 7],

[2, 4, 7, 8],

[3, 5, 9, 10]

给出target = 3,返回 2
比较简单,从左下角开始,比较数组中的数字和目标值的大小,如果一样大,向上并向右移,如果目标值比较大,向右移,如果数组中的数比较大,则上移:

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.empty()) return 0;
        int count = 0;
        int i = matrix.size()-1,j = 0;
        while (i >= 0 && j < matrix[0].size()) {
            if (matrix[i][j] == target) {
                count++;
                i--;
                j++;
            }
            else if (matrix[i][j] < target) j++;
            else i--;
        }
        return count;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读