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.
解法一
思路
这题就是说确定矩形的长和宽,使得面积与给定值相等,而且长宽尽可能接近。那么最优解就是长宽相等而且面积相等了,即x * x = area
,但是这样的整数x
却不一定存在。既然我们知道了x
的最优取值,接下来就只需要将x
逐步增大,直到出现area % x == 0
,即存在整数x
、y
使得x * y = area
就好了。
Python
class Solution(object):
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
x = int(math.ceil(area ** 0.5))
while area % x != 0:
x += 1
y = int(area / x)
return [x, y]
Java
public class Solution {
public int[] constructRectangle(int area) {
int x = (int) Math.ceil(Math.sqrt(area));
while (area % x != 0) {
x++;
}
int y = area / x;
return new int[] {x, y};
}
}
C++
class Solution {
public:
vector<int> constructRectangle(int area) {
int x = (int) ceil(sqrt(area));
while (area % x != 0) {
x++;
}
int y = area / x;
return vector<int> {x, y};
}
};