当前位置: 代码迷 >> 综合 >> 【数学】C033_范围求和II(暴力 | 脑筋急转弯)
  详细解决方案

【数学】C033_范围求和II(暴力 | 脑筋急转弯)

热度:48   发布时间:2024-01-25 16:16:18.0

一、题目描述

Given an mn 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.

二、题解

(1) 暴力(超时)

/*** @thought:暴力破解(超时):** 因为a>0,b>0,故每一个操作都会涉及到M[0][0],故我们完成每个操作后,* 再次遍历矩阵,看有多少个元素是等于M[0][0]就知道最大元素有多少个了*/
public int maxCount(int m, int n, int[][] ops) {int[][] M = new int[m][n];int maxCount = 0;for(int[] op : ops)for (int i = 0; i < op[0]; i++)for (int j = 0; j < op[1]; j++)M[i][j]++;for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if(M[i][j]==M[0][0])maxCount++;return maxCount;
}

复杂度分析

  • 时间复杂度: O ( x ? m ? n ) O(x*m*n) x x o p s ops 数组的行数。
  • 空间复杂度: O ( m ? n ) O(m*n)

(2) 脑筋急转弯

/*** @thought:脑筋急转弯:因为a影响矩阵M的每一行的元素,b影响每一列的元素。* 因此,对于最小的a1和b1,其他ai和bi的操作范围都会覆盖a1,b1,* 故我们只需找出被操作的最小面积即可(即 a1*b1)** @date: 1/17/2020 3:49 PM* @Execution info:* ·执行用时 0 ms 击败了 100% 的java用户* ·内存消耗 MB 击败了 % 的java用户* @Asymptotic Time Complexity:O()*/
public int maxCount2(int m, int n, int[][] ops) {for (int[] op : ops) {if(op[0] < m)  m=op[0];if(op[1] < n)  n=op[1];}return m * n;
}

复杂度分析

  • 时间复杂度: O ( x ) O(x) x x o p s ops 数组的行数。
  • 空间复杂度: O ( 1 ) O(1)