1、遍历判断
遍历1到area,判断整除后的数是否大于当前数,如果是,判断两者之差是否为最小;如果不大于当前数,返回结果。
代码
class Solution:
def constructRectangle(self, area: int) -> List[int]:
diff = area
minlength, minwide = 0,0
for wide in range(1, area+1, 1):
length = area // wide
if length >= wide:
if area % wide == 0 and length - wide < diff:
minlength = length
minwide = wide
else:
return [minlength, minwide]
return [minlength, minwide]
2、开方判断
如果area为4、9之类可开方的数值,此时长宽相同,差值最小,为0;所以当area的约数,也就是宽,从area的开方值向下取整,然后找到第一个可被area整除的整数,即是需要的宽。
代码
class Solution:
def constructRectangle(self, area: int) -> List[int]:
temp = int(area ** (1/2))
for wide in range(temp, 0, -1):
if area % wide == 0:
return[area//wide, wide]
链接:https://leetcode-cn.com/problems/construct-the-rectangle/solution/492-gou-zao-ju-xing-by-senlindu-abvy/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。