zoukankan      html  css  js  c++  java
  • LintCode-38.搜索二维矩阵 II

    搜索二维矩阵 II

    写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。

    • 这个矩阵具有以下特性:
    • 每行中的整数从左到右是排序的。
    • 每一列的整数从上到下是排序的。
    • 在每一行或每一列中没有重复的整数。

    样例

    考虑下列矩阵:
    [
         [1, 3, 5, 7],
         [2, 4, 7, 8],
         [3, 5, 9, 10]
    ]
    给出target = 3,返回 2

    挑战

    要求O(m+n) 时间复杂度和O(1) 额外空间

    标签

    Sorted Matrix 谷歌 矩阵

    code

    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
            int row_count = matrix.size();      //  行数
            int col_count = 0;                  //  列数
            if(row_count != 0)
                col_count = matrix[0].size();
            int tar_count = 0,i,j;
    
            for(i=0; i<row_count && row_count!=0 && col_count!=0; i++) {
                for(j=0; j<col_count; j++) {
                    if(matrix[i][j] == target)
                        tar_count++;
                    if(matrix[i][j] > target)
                        break;
                }
            }
            return tar_count;
        }
    };
  • 相关阅读:
    解决CollectionView TableView reloadData或者reloadSections时的刷新的闪烁问题
    HTTP请求头
    Fastlane 使用笔记
    python-函数式编程
    python-高级特性
    python基础使用
    python基础-函数02
    python基础-函数01
    python基础
    Linux基础
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6806611.html
Copyright © 2011-2022 走看看