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:
The area of the rectangular web page you designed must equal to the given target area.
The width W should not be larger than the length L, which means L >= W.
The difference between length L and width W should be as small as possible.
作为一名菜鸟首先上来的肯定就是暴力解法,但是最后暴力解法会超时,就放在后面再说了。
现在先说简单的解法。
第一步,是将target因式分解,两个数相乘等于target,那么这两个数最大可能是多少。(很容易入坑的是,除以2,但是实际上,也是重复了不少,因为比如9,9//2=4,事实上是重复了2的,所以应该用开方来解决)
那么就找到中间值mid=int(math.sqrt(area))
第二步,从mid开始判断能否被target整除(这样做能够保证3.L和W之差最小)
第三步,若能返回[area//mid,mid](这样保证了2. 即长比宽要大)若不能,mid减一直到mid=1,返回[area,1]
代码如下:
class Solution(object):
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
w = int(math.sqrt(area))
while area % w != 0:
w -= 1
return area//w, w
下面将记录一下我的菜鸡代码:
class Solution(object):
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
res = [[area-1,area,1]]
for i in range(2,area+1):
if not area%i and area//i >= i:
res.append([area//i-i,area//i,i])##找出所有可能存在的情况
return min(res)[1:] ##返回差距最小的一组
总结,其实就是没用搞清楚从哪里开始导致了我的版本过于复杂。时间、空间成本太大了。