492.布局矩形(javascript)492.ConstructtheRectangle
原创作为一位web开发者, 知道如何规划页面大小非常重要。 因此,给定一个特定的矩形页面区域,您的任务是设计一个长度 L 和宽度为 W 以及满足以下要求的矩形页面。要求:
- 您设计的矩形页面必须等于给定的目标区域。
- 宽度 W 不应大于长度 L 换句话说,要求 L >= W 。
- 长度 L 和宽度 W 间隙应尽可能小。
返回一个 数组 [L, W],其中 L 和 W 它是您按顺序设计的网页的长度和宽度。
A web developer needs to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area.
The width W should not be larger than the length L, which means L >= W.
The difference between length L and width W should be as small as possible.
Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.
示例1:
输入: 4
输出: [2, 2]
解释: 目标区域是 4, 所有可能的施工方案 [1,4], [2,2], [4,1]。
但应要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更符合要求。. 所以输出长度 L 为 2, 宽度 W 为 2。
示例 2:
输入: area = 37
输出: [37,1]
示例 3:
输入: area = 122122
输出: [427,286]
想法来源: https://leetcode-cn.com/problems/construct-the-rectangle/solution/gou-zao-ju-xing-by-leetcode-solution-dest/
不可能有太多的食物-_-
- L·W=area,这意味着area可以被W整除
- L>=W,结合要求1,可得area=L·W>=W·W ,从而获得√ area>=W
- 这意味着 W 应取满足area 可以被 W 整除且 √ area>=W最大值。
从ath.sqrt(area)开始获取值area % w == 0,否则将退出循环。 W 一次还原后继续循环。
var constructRectangle = function (area) {
let w = Math.floor(Math.sqrt(area));
while (area % w != 0) {
w--
}
return [Math.floor(area/w),w]
};
leetcode: https://leetcode-cn.com/problems/construct-the-rectangle/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123




