Skip to content

Latest commit

 

History

History
 
 

1725.Number Of Rectangles That Can Form The Largest Square

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
comments difficulty edit_url rating source tags
true
简单
1229
第 224 场周赛 Q1
数组

English Version

题目描述

给你一个数组 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 个矩形的长度为 li 、宽度为 wi

如果存在 k 同时满足 k <= lik <= wi ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 4 的正方形。

maxLen 为可以从矩形数组 rectangles 切分得到的 最大正方形 的边长。

请你统计有多少个矩形能够切出边长为 maxLen 的正方形,并返回矩形 数目

 

示例 1:

输入:rectangles = [[5,8],[3,9],[5,12],[16,5]]
输出:3
解释:能从每个矩形中切出的最大正方形边长分别是 [5,3,5,5] 。
最大正方形的边长为 5 ,可以由 3 个矩形切分得到。

示例 2:

输入:rectangles = [[2,3],[3,7],[4,3],[3,7]]
输出:3

 

提示:

  • 1 <= rectangles.length <= 1000
  • rectangles[i].length == 2
  • 1 <= li, wi <= 109
  • li != wi

解法

方法一:一次遍历

我们定义一个变量 $ans$ 来记录当前最大边长的正方形的个数,定义另一个变量 $mx$ 来记录当前最大的边长。

遍历数组 $rectangles$,对于每个矩形 $[l, w]$,我们取 $x = \min(l, w)$,如果 $mx &lt; x$,说明我们找到了一个更大的边长,此时我们将 $mx$ 更新为 $x$,并将 $ans$ 更新为 $1$;如果 $mx = x$,说明我们找到了一个和当前最大边长相同的边长,此时我们将 $ans$ 增加 $1$

最后返回 $ans$ 即可。

时间复杂度 $O(n)$,其中 $n$ 为数组 $rectangles$ 的长度。空间复杂度 $O(1)$

Python3

class Solution:
    def countGoodRectangles(self, rectangles: List[List[int]]) -> int:
        ans = mx = 0
        for l, w in rectangles:
            x = min(l, w)
            if mx < x:
                ans = 1
                mx = x
            elif mx == x:
                ans += 1
        return ans

Java

class Solution {
    public int countGoodRectangles(int[][] rectangles) {
        int ans = 0, mx = 0;
        for (var e : rectangles) {
            int x = Math.min(e[0], e[1]);
            if (mx < x) {
                mx = x;
                ans = 1;
            } else if (mx == x) {
                ++ans;
            }
        }
        return ans;
    }
}

C++

class Solution {
public:
    int countGoodRectangles(vector<vector<int>>& rectangles) {
        int ans = 0, mx = 0;
        for (auto& e : rectangles) {
            int x = min(e[0], e[1]);
            if (mx < x) {
                mx = x;
                ans = 1;
            } else if (mx == x) {
                ++ans;
            }
        }
        return ans;
    }
};

Go

func countGoodRectangles(rectangles [][]int) (ans int) {
	mx := 0
	for _, e := range rectangles {
		x := min(e[0], e[1])
		if mx < x {
			mx = x
			ans = 1
		} else if mx == x {
			ans++
		}
	}
	return
}

TypeScript

function countGoodRectangles(rectangles: number[][]): number {
    let [ans, mx] = [0, 0];
    for (const [l, w] of rectangles) {
        const x = Math.min(l, w);
        if (mx < x) {
            mx = x;
            ans = 1;
        } else if (mx === x) {
            ++ans;
        }
    }
    return ans;
}