LeetCode每日一题: 1725. 可以形成最大正方形的矩形数目, 遍历

169 阅读1分钟

PK创意闹新春,我正在参加「春节创意投稿大赛」,详情请看:春节创意投稿大赛

image.png

class Solution {
    public int countGoodRectangles(int[][] rectangles) {
        int max = Math.min(rectangles[0][0], rectangles[0][1]);
        int total = 0;
        for (int[] rectangle : rectangles) {
            int min = Math.min(rectangle[0], rectangle[1]);
            if (max < min) {
                max = min;
                total = 0;
            }
            if (max == min){
                total ++;
            }
        }
        return total;
    }
}

思路: 查询每个数组里最小的数值, 因为矩形切割为正方形肯定是以最小的边为边. 遍历时记录目前的最大值max并记录出现次数total, 如果发现又出现更大的边, 则清空次数total, 最后返回最大边出现次数total