[leetcode]: 492. Construct the Rectangle

来源:互联网 发布:sendmail php 编辑:程序博客网 时间:2024/06/17 15:36

1.题目描述

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.

翻译:给定义个矩形的面积,求长L和宽W。要求:面积固定,W<=L,L-W尽可能小。
例如:输入4,可能的长宽组合有[(1,4),(2,2),(4,1)],(2,2)符合要求。

2.分析

(1)L和W的差距尽可能小,就从正方形开始考虑sqrt(area).
(2)正方形不满足面积相等,L增大,W减小。直到满足面积相等。

3代码

c++

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