LeetCode笔记:492. Construct the Rectangle

问题(Easy):

For a web developer, it is very important 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:

  1. The area of the rectangular web page you designed must equal to the given target area.
  2. The width W should not be larger than the length L, which means L >= W.
  3. The difference between length L and width W should be as small as possible.

You need to output the length L and the width W of the web page you designed in sequence.
Example:
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Note:

  1. The given area won't exceed 10,000,000 and is a positive integer
  2. The web page's width and length you designed must be positive integers.

大意:

对于一个网站开发者,知道如何设计网站尺寸是很重要的。所以,给出一个特定的矩形网站区域面积,你的工作是设计一个矩形网站界面,其长L和宽W需要满足下面的要求:

  1. 你设计的矩形网站区域的面积必须等于给出的目标面积。
  2. 宽度W不能大于长度L,也就是L>=W。
  3. 长L和宽W之间的差距必须尽可能小。

你需要输出网站界面的长L和宽W。
比如:
输入:4
输出:[2, 2]
解释:目标面积是4,所有可能的结构方式是 [1,4], [2,2], [4,1]。但是根据要求2,[1, 4] 不合格;根据要求3,[4, 1] 比起 [2, 2] 不是最佳的。所以长度L是2,宽度W也是2。

注意:

  1. 给出的面积不会超过 10,000,000 并且是正数。
  2. 你设计的网站界面的宽度和长度必须是正数。

思路:

令W从1开始,L此时等于面积本身。然后循环让W加一,同时计算是否有对应的L可以让其积正好等于面积,有的话判断L是否大于W,满足要求就可以更新最后的W和L了,一直循环下去直到W大于L就不要算了。这种方法比较慢。

C++:

class Solution {
public:
    vector constructRectangle(int area) {
        int tempL = area, tempW = 1;
        int L = tempL, W = tempW;
        while (tempL >= tempW) {
            tempW++;
            if (area % tempW == 0) {
                tempL = area / tempW;
                if (tempL >= tempW) {
                    L = tempL;
                    W = tempW;
                } else {
                    break;
                }
            }
        }
        return {L, W};
    }
};

他山之石:

之前想过用开平方根来从中间开始找,但总想着要两头跑L和W,步长不好确定,其实只需要开根后递减W,计算最先遇到的一个可以用面积整除的W,此时就是距离最近的L和W了。速度比上个方法会快很多。

class Solution {
public:
    vector constructRectangle(int area) {
        int w = sqrt(area);
        while (area%w != 0) {
            w--;
        }
        return {area/w, w};
    }
};

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首页

你可能感兴趣的:(LeetCode笔记:492. Construct the Rectangle)