前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-598-Range Addition II

leetcode-598-Range Addition II

作者头像
chenjx85
发布2018-07-05 16:16:53
3340
发布2018-07-05 16:16:53
举报

题目描述:

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:

  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<vector<int>>& 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<s1;i++)//统计出所有操作都改变了前几行,都改变了前几列
        {
            a=min(a,ops[i][0]);
            b=min(b,ops[i][1]);
        }
        return a*b;//最后返回改变的行数*列数
    }

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档