您的位置:首页 > 其它

LintCode "Search a 2D Matrix II"

2015-09-23 05:19 357 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: