1725. 可以形成最大正方形的矩形數目
給你一個數組 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 個矩形的長度為 li 、寬度為 wi 。
如果存在 k 同時滿足 k <= li 和 k <= 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
解題思路
- 先進行一次遍歷rectangles,計算出每個矩形可以裁出的最大正方形的邊長,比較得出可以從矩形數組 rectangles 切分得到的 最大正方形 的邊長maxLen。
- 再進行一次遍歷rectangles,統計有多少個矩形能夠切出邊長為 maxLen 的正方形
代碼
class Solution {
public:int countGoodRectangles(vector<vector<int>>& rectangles) {int max_len(0);for(auto item:rectangles){max_len=max(min(item[0],item[1]),max_len);}int res(0);for(auto item:rectangles){if (min(item[0],item[1])==max_len) res++;}return res;}
};
優化思路
只進行一次遍歷rectangles,在遍歷的過程中,如果出現了比當前maxLen更大的正方形長度,則替換當前maxLen,并將記錄maxLen正方形個數的變量res置為1,如果出現了和maxLen相等的正方形大小,則將記錄maxLen正方形個數的變量res加一。
代碼
class Solution {
public:int countGoodRectangles(vector<vector<int>>& rectangles) {int max_len(0),res(0);for(auto item:rectangles){int cur=min(item[0],item[1]);if (cur>max_len){max_len=cur; res=1;} else if (cur==max_len){res++;}}return res;}
};