1. 程式人生 > >Leetcode——598. Range Addition II

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 positive integers 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:

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

解題思路

首先我在看這道題的時候,看的有點雲裡霧裡,沒咋看懂,後來看別人的分析終於是看懂了!

這道題的大概意思呢就是:
給定一個m*n的矩陣,這個矩陣中元素的初始值為0,然後用引數ops二維陣列去更新矩陣中的每個元素值,如a = 2, b = 2,則將矩陣中下標 [0][0] 、[0][1]、[1][0]、[1][1]元素都加1,依次類推,在將矩陣中的所有元素操作完成後,要找到矩陣中最大元素的個數,並返回

這個題的解法不是很難,因為首先要找到最大的元素,那要考慮的問題就是,什麼樣的元素是最大的,肯定是被操作的次數最多的當然就是最大的,因為沒操作一次就會增加1。所以問題就轉變為,找給定的二維陣列中重疊的行和列的個數,能夠重疊的行和列當然就是所給的二維陣列中第一列最小的值和第二列最小的值啦。所以所求的結果就是將這兩個最小值相乘

所以為覺得,這類題,主要是考察理解題的能力,和題轉換為數學模型的能力。

AC程式碼

class Solution {
    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;
    }
}