首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode笔记:492. Construct the Rectangle

LeetCode笔记:492. Construct the Rectangle

作者头像
Cloudox
发布2021-11-23 16:21:21
发布2021-11-23 16:21:21
2760
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题(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++:

代码语言:javascript
复制
class Solution {
public:
    vector<int> 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了。速度比上个方法会快很多。

代码语言:javascript
复制
class Solution {
public:
    vector<int> constructRectangle(int area) {
        int w = sqrt(area);
        while (area%w != 0) {
            w--;
        }
        return {area/w, w};
    }
};

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/2/26 上,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题(Easy):
  • 大意:
  • 思路:
  • C++:
  • 他山之石:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档