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