码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Search a 2D Matrix II"

时间:2015-09-23 06:46:28      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

 

LintCode "Search a 2D Matrix II"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4831111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!