leetcode-492-Construct the Rectangle
Posted chenjx85
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-492-Construct the Rectangle相关的知识,希望对你有一定的参考价值。
题目描述:
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:
- The given area won‘t exceed 10,000,000 and is a positive integer
- The web page‘s width and length you designed must be positive integers.
要完成的函数:
vector<int> constructRectangle(int area)
说明:
1、这道题目不难,给定一个乘积,要求输出两个因子(大的在前,小的在后),两个因子的差应该越小越好。
2、看到这些限定条件,我们首选就是开方,然后在开方得到的数值附近找到一个乘积能够整除的数。
代码如下:
vector<int> constructRectangle(int area)
{
int eu=ceil(sqrt(area));
while(area%eu)
eu+=1;
return {eu,area/eu};
}
上述代码accepted,实测80ms,beats 27.85% of cpp submissions……
这么低的吗?但我看评论区的代码采用的也是跟我一样的方法,为什么他们就能4ms……
3、改进:
细细对比了一下评论区的代码,他们采用的是eu不断地减一,而我用的是eu不断地加一。
因为eu小的话比较容易除?比如2889除以11,跟2889除以3比起来,肯定后者比较好做除法。
所以如果采用eu不断地减一的方法,的确能够节省很多做除法的时间,而两者的效果是一样的。
代码如下:
vector<int> constructRectangle(int area)
{
int eu=floor(sqrt(area));
while(area%eu)
eu-=1;
return {area/eu,eu};
}
实测3ms,beats 98.48% of cpp submissions。
以上是关于leetcode-492-Construct the Rectangle的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 492. Construct the Rectangle_Easy tag: Math