算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 范围求和 II,我们先来看题面:
https://leetcode-cn.com/problems/range-addition-ii/
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
给你一个 m x n 的矩阵 M ,初始化时所有的 0 和一个操作数组 op ,其中 ops[i] = [ai, bi] 意味着当所有的 0 <= x < ai 和 0 <= y < bi 时, M[x][y] 应该加 1。
在 执行完所有操作后 ,计算并返回 矩阵中最大整数的个数 。
示例
解题
https://blog.csdn.net/weixin_44171872/article/details/107946401
由于所有的范围都是从左上角开始的,故最大值的个数就是操作次数最多的左上角的范围,故只需要保存左上角操作过的最小重叠范围即可;
class Solution {
public:
int maxCount(int m, int n, vector<vector<int>>& ops) {
int min_row=m;
int min_col=n;
//求取最小的左上角的范围
for(int i=0;i<ops.size();++i){
min_col=min(min_col,ops[i][1]);
min_row=min(min_row,ops[i][0]);
}
return min_col*min_row;
}
};
上期推文: