leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和]
2024-08-29 20:22:42
Given a m x n
matrix mat
and an integer threshold
. Return the maximum side-length of a square with a sum less than or equal to threshold
or return 0 if there is no such square.
Example 1:
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0
Example 3:
Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
Output: 3
Example 4:
Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
Output: 2
Constraints:
1 <= m, n <= 300
m == mat.length
n == mat[i].length
0 <= mat[i][j] <= 10000
0 <= threshold <= 10^5
给定一个矩阵,找出一个最大正方形的边长,这个正方形中元素和要小于threshold。
解法:
二维前缀和,sum[i][j]表示从[0][0]到[i][j]的矩形的元素和,有了这个sum后,就可以用 O(row * col * min(row,col)) 的时间复杂度遍历所有的正方形。
class Solution {
public:
int maxSideLength(vector<vector<int>>& mat, int threshold) {
int row = mat.size(), col = mat[].size();
vector<vector<int>> sum(row+, vector<int>(col+, ));
for(int i=; i<=row; i++)
for(int j=; j<=col; j++)
sum[i][j] = sum[i-][j]+sum[i][j-]-sum[i-][j-]+mat[i-][j-];
int ret = ;
for(int i=; i<=row; i++)
for(int j=; j<=col; j++){
for(int k=; k<=min(i, j); k++){
int temp = sum[i][j]-sum[i-k][j]-sum[i][j-k]+sum[i-k][j-k];
if(temp <= threshold)
ret = max(ret, k);
}
}
return ret;
}
};
最新文章
- android中返回键捕获处理
- [MSSQL2008]Spatial Data in SQL Server 2008 - 根据经纬度计算两点间距离
- Windows 2012 安装 .net framework 3.5
- 比较body.onload(function())、$(document).ready(function())与$(windows).load(function)
- Andriod Dialog 加载框 自定义,公用
- Android Bitmap详细介绍
- 【python cookbook】【字符串与文本】9.将Unicode文本统一表示为规范形式
- IOS静态库和Framework区别
- QT:使用“状态模式”绘制界面
- logger日志工具类
- js中的innerHTML和outerHTML区别
- Linux下自动化监控内存、存储空间!
- 监督学习——logistic进行二分类(python)
- 初始Oracle
- Xamarin.Forms 3.0的新特性
- jq简单仿上传文件
- 阿里云流计算专场-GitHub上相关文档
- PAT 1035 插入与归并(25)(代码+思路+测试点分析)
- Android Dialog的整个生命周期
- python将response中的cookies加入到header
热门文章
- HAWQ技术总结
- Java 基础-异常处理
- c++调用c#代码
- C# 捕获全局异常
- SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思 sql server 2005 2008
- html—倒计时demo
- 转 jvisualvm 工具使用 https://www.cnblogs.com/kongzhongqijing/articles/3625340.html
- RocketMQ安装部署及整合Springboot
- 将查询列表内容保存到excel表格中,并保存到相应的盘中
- CentOS6 破解登录密码