博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode-598-Range Addition II
阅读量:7029 次
发布时间:2019-06-28

本文共 1635 字,大约阅读时间需要 5 分钟。

题目描述:

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 = 3operations = [[2,2],[3,3]]Output: 4Explanation: 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.

 

要完成的函数:

int maxCount(int m, int n, vector<vector<int>>& ops) 

 

说明:

1、这道题给定一个m行n列的矩阵,矩阵所有数值都是0。

还给定了操作,放在二维矩阵中,比如[[2,2],[3,3]]这种形式,代表两个操作。

第一个操作是对0<=i<2和0<=j<2的子矩阵所有元素都加1。矩阵变化为[[1,1,0],[1,1,0],[0,0,0]]。

第二个操作是对0<=i<3和0<=j<3的子矩阵所有元素都加1。矩阵变化为[[2,2,1],[2,2,1],[1,1,1]]。

最后返回矩阵中数值最大的元素有几个,上述矩阵数值最大为2,一共有4个,返回4,。

 

2、上述题目似乎要对矩阵进行一个又一个的操作,最后再进行统计。

但我们也可以不改变矩阵数值,直接返回最后有多少个最大数值的矩阵元素就好。矩阵初始化为0为我们提供了这样做的可能性。

我们只需统计出所有这些操作都改变了哪些元素,哪些元素在每一次操作中都会加1。

最后返回这些元素的个数就好了。

代码如下:

int maxCount(int m, int n, vector
>& ops) { int s1=ops.size(); if(s1==0)//边界情况,操作的矩阵是空的 return m*n; int a=ops[0][0],b=ops[0][1]; for(int i=1;i

上述代码实测9ms,beats 99.52% of cpp submissions。

转载于:https://www.cnblogs.com/chenjx85/p/9159515.html

你可能感兴趣的文章
通读SDWebImage①--总体梳理、下载和缓存
查看>>
929. 独特的电子邮件地址
查看>>
19. Spring Boot Shiro 权限管理
查看>>
【C语言】14-返回指针的函数与指向函数的指针
查看>>
uoj#119. 【UR #8】决战圆锥曲线(线段树+复杂度分析)
查看>>
docker 13 dockerfile的保留字指令
查看>>
(转)开放window是服务器端口——以8080为例
查看>>
C# 通过IEnumberable接口和IEnumerator接口实现泛型和非泛型自定义集合类型foreach功能...
查看>>
微信小程序初识
查看>>
Ubuntu中打开RAR文件
查看>>
数字转换大写人民币的delphi实现
查看>>
开源的asp.net工作流程引擎。 http://ccflow.org
查看>>
日期和时间字符串格式化
查看>>
POJ2774:Long Long Message——题解
查看>>
javascript作用域与预解析
查看>>
C# 中的拓展方法,以StringBuilder加上IndexOf方法举例
查看>>
第41件事 创新设计的4种方法
查看>>
用半监督算法做文本分类
查看>>
【2802】SDUTOJ (并查集模板水题2)
查看>>
看书不挑出版社的都是山炮——评60家国内出版社
查看>>