题目:
A web developer needs 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.
Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.
给定一方形的面积,回传符合面积的[长,宽]
其中长宽为整数,长要大于宽,且长宽差距越小越好
长宽差距越小越好,表示长宽要尽量接近正方形
class Solution: def constructRectangle(self, area: int) -> List[int]: x=int(sqrt(area)) while True: if area%x==0: return [area//x,x] else: x=x-1
我们由宽(x)为int(sqrt(area))开始推
即由正方形慢慢往长方形的方向推
直到area能被x整除为止,x不断减1
一旦能整除代表我们发现了差距最小的长宽,立即回传当下长宽
最后执行时间36ms(faster than 91.88%)
那我们下题见