算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 构造矩形,我们先来看题面:
https://leetcode-cn.com/problems/construct-the-rectangle/
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.
作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:
2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。
3. 长度 L 和宽度 W 之间的差距应当尽可能小。
你需要按顺序输出你设计的页面的长度 L 和宽度 W。
示例
输入: 4
输出: [2, 2]
解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。
但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。
说明:
给定的面积不大于 10,000,000 且为正整数。
你设计的页面的长度和宽度必须都是正整数。
解题
这一题的解法比较独特,我们观察题目给出的条件 L >= W ,通过这一点 我们可以得出 W * W <= L * W = area
那么我们可以利用Math提供的平方根函数对area 开方得出 w 可能出现的最大值,随后递减 w 的值,直到它能够被 area 取模为0;此时的 w 就是符合题目条件的最接近 L 的 W;
class Solution {
public int[] constructRectangle(int area) {
int w = (int)Math.sqrt(area);
while(area % w != 0) w--;
return new int[]{area / w, w};
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
本篇文章来源于微信公众号:程序IT圈
原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/18001.html