zoukankan      html  css  js  c++  java
  • LeetCode 598. Range Addition II

    Given an m * n matrix M initialized with all 0's and several update operations.

    Operations are represented by a 2D array, and each operation is represented by an array with two positiveintegers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.

    You need to count and return the number of maximum integers in the matrix after performing all the operations.

    Example 1:

    Input: 
    m = 3, n = 3
    operations = [[2,2],[3,3]]
    Output: 4
    Explanation: 
    Initially, M = 
    [[0, 0, 0],
     [0, 0, 0],
     [0, 0, 0]]
    
    After performing [2,2], M = 
    [[1, 1, 0],
     [1, 1, 0],
     [0, 0, 0]]
    
    After performing [3,3], M = 
    [[2, 2, 1],
     [2, 2, 1],
     [1, 1, 1]]
    
    So the maximum integer in M is 2, and there are four of it in M. So return 4.

    Note:

    1. The range of m and n is [1,40000].
    2. The range of a is [1,m], and the range of b is [1,n].
    3. The range of operations size won't exceed 10,000.

    题意:给定一个m * n的矩阵M,首先将矩阵M的所有元素初始化为0,然后对矩阵M进行更新操作。
    更新操作的定义:每个操作用一个由两个正整数a、b组成的数组[a,b]表示,i表示矩阵M的行,j表示矩阵M的列;
    [a,b]的含义为:对1 <= i <= a,1 <= j <= b的所有元素进行加1操作。
    执行完所有操作后,返回矩阵中最大整数的个数。

    思路:将二维数组ops看作一个m * 2的矩阵N,即相当于求矩阵N中每一列的最小值

    public int maxCount(int m, int n, int[][] ops) {
            if(ops == null)
                return 0;
            int row = Integer.MAX_VALUE, col = Integer.MAX_VALUE;
            for(int i = 0; i < ops.length; i++){
                if(row > ops[i][0])
                    row = ops[i][0];
                if(col > ops[i][1])
                    col = ops[i][1];
            }
            return row * col;
        }

    LeetCode提供的方法思路一样,但算法更简洁

    public int maxCount(int m, int n, int[][] ops){
            for(int[] op : ops){
                m = Math.min(m, op[0]);
                n = Math.min(n, op[1]);
            }
            return m * n;
        }
  • 相关阅读:
    pytest学习(2)
    pytest学习(1)
    facets学习(1):什么是facets
    window10下部署flask系统(apache和wsgi)
    python tips:列表推导
    python的一致性(1)sorted和len
    THULAC:一个高效的中文词法分析工具包(z'z)
    EAScript 2016的新增语法(1)
    python的property的用法
    python算法:LinkedList(双向线性链表)的实现
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8283341.html
Copyright © 2011-2022 走看看