Open carloscn opened 1 year ago
use std::collections::HashMap;
pub fn count_good_rectangles(rectangles: Vec<Vec<i32>>) -> i32
{
if rectangles.len() < 1 {
return 0;
}
let ret:i32;
let mut r_v:Vec<i32> = vec![];
for e in rectangles {
let min = e.iter().fold(i32::MAX, |a: i32, b| a.min(*b));
r_v.push(min);
}
// find max frequency of an element in the vector
let mut m:HashMap<i32, usize> = HashMap::new();
for x in &r_v {
*m.entry(*x).or_default() += 1;
}
let max_freq = m.into_iter()
.max_by_key(|(_, v)| *v)
.map(|(k, _) | k)
.unwrap() as i32;
// // optional:
// let max_freq = r_v.clone().into_iter()
// .fold(HashMap::<i32, i32>::new(), |mut m, x| {
// *m.entry(x).or_default() += 1; m })
// .into_iter()
// .max_by_key(|(_, v)| *v)
// .map(|(k, _) | k)
// .unwrap();
// count number of max frequency of an element in the vector
ret = r_v.iter().fold(0, |count, b| {
if *b == max_freq {
count + 1
} else {
count
}
});
return ret;
}
问题描述
给你一个数组 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
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/number-of-rectangles-that-can-form-the-largest-square