leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段

Posted Jason333

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段相关的知识,希望对你有一定的参考价值。

题目链接

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[0].size();
        vector<vector<int>> sum(row+1, vector<int>(col+1, 0));
        for(int i=1; i<=row; i++)
            for(int j=1; j<=col; j++)
                sum[i][j] = sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+mat[i-1][j-1];
        int ret = 0;
        for(int i=1; i<=row; i++)
            for(int j=1; j<=col; j++){
                for(int k=1; 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;
    }
};

 

以上是关于leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段的主要内容,如果未能解决你的问题,请参考以下文章

Baozi Leetcode solution 1292. Maximum Side Length of a Square with Sum Less than or Equal to Th

声源定位 球面散乱数据插值方法/似然估计hybrid spherical interpolation/maximum likelihood (SI/ML) 麦克风阵列声源定位

LeetCode--689_Maximum_Sum_of_3_NonOverlapping_Subarrays

LeetCode maximum binary tree

LeetCode maximum binary tree

LeetCode 70 _ Maximum Subarray 最大子数组 (Easy)