Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Simply a revise of a genius Greedy algorithm seen on LeetCode - linear walking.

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> > &m, int target) 
    {
        int cnt = 0;
        int h = m.size();
        if (!h) return cnt;
        int w = m[0].size();

        int x = w - 1, y = 0;
        while( (x >= 0 && x < w) && (y >= 0 && y < h))
        {
            int v = m[y][x];
            if (v <= target)
            {
                cnt += v == target;
                y ++;
            }
            else
            {
                x --;
            }
        }
        return cnt;
    }
};

 

posted on 2015-09-23 05:19  Tonix  阅读(131)  评论(0编辑  收藏  举报