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:

  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.

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.
这道题的意思是:给定一个m*n的矩阵,把数组初始化为0,然后用ops二维数组去更新矩阵的每个元素值,例如a=2,b=2则矩阵M11-M22全部增加1,以此类推,然后找出最大的元素的个数。
为了解这道题,需要去找进行操作的次数最多的min_row行和min_col列,这样min_row*min_col就是要返回的值。因为每次进行更新操作时,必然从M11-Mab,即从第一个元素到第a行b列的元素,这样只需要找最小的a(即min_row)和最小的b(即min_col),即可,代码如下:
         int min_row = 40000;
   	 int min_col = 40000;
   	 int len = ops.length;
   	 for(int i=0;i<len;i++){
   		 //下面两句分别是为了求最小的a和b,因为ops的每一行第一个元素是a,第二个是b
   		 min_row = Math.min(min_row, ops[i][0]);
   		 //System.out.println(min_row);
   		 min_col = Math.min(min_col, ops[i][1]);
   		 //System.out.println(min_col);
   	 }
   	 min_row = Math.min(min_row,m);
   	 min_col = Math.min(min_col,n);
   	 return min_row*min_col;
另一种更简洁的写法:
        for(int [] op :ops){
    		m = Math.min(m, op[0]);
    		n = Math.min(n, op[1]);
    	}
    	return m*n;

端午节快乐~~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值