题目在这​​:https://leetcode-cn.com/problems/construct-the-rectangle/​

思路分析:

题目中所说的构造矩形,其实可以是我们认知里的正方形。毕竟严格来讲正方形也是一种特殊的矩形。所以这里要注意。

题目要求找到长和宽的差值最小的哪一种分配方法。
并且宽度不可能超过总面积的开方值。
比如 总面积为4 则宽为1或者2 , 总面积为10 则宽为2或者1。

所以我们直接从面积的开方值处向1遍历。
如果找到 面积 / 宽 为正整数的情况下,说明已经找到了长,此时也是长和宽差值最小的情况。

完整代码:

class Solution:
def constructRectangle(self, area: int) -> List[int]:
import math
w = int(math.sqrt(area))
while w >= 1:
if area % w == 0:
return [area//w,w]
w -=1