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

【Lintcode】038.Search a 2D Matrix II

时间:2017-05-07 22:00:13      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:each   code   lists   win   log   column   bsp   ntc   sts   

题目:

Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.

This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • Integers in each column are sorted from up to bottom.
  • No duplicate integers in each row or column.

题解:

 

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) {
        if (matrix.empty() || matrix[0].empty()) {
            return 0;
        }
        
        int cnt = 0;
        int m = matrix.size(), n = matrix[0].size();
        
        for (int i = 0, j = n - 1; i < m && j >= 0; ) {
            if (matrix[i][j] == target) {
                cnt++;
            }
            if (matrix[i][j] > target) {
                --j;
            } else {
                ++i;
            }
        }
        
        return cnt;
    }
};

 

【Lintcode】038.Search a 2D Matrix II

标签:each   code   lists   win   log   column   bsp   ntc   sts   

原文地址:http://www.cnblogs.com/Atanisi/p/6821965.html

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