492 Construct the Rectangle
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 lengthL
, which meansL >= W
.The difference between length
L
and widthW
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.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= area <= 10^7
这题想复杂了,一眼看上去是不是二分呀,从一半开始,找到area那么大的数里,最小的能被整除的数。因为靠近中间diff才小。然而,二分写不出来,因为判断的条件好像不能一下砍一半。后来又想了想,是不是two pointer,从大小两边往中间找。但又不太像,因为不能两边同时移动。而且没有判断到底该移哪一边的条件。后来看了提示,还是没想出来。最后只好看答案了。其实,这里的范围因该是1到 sqrt(area),这是width的范围。没有什么更快的方式,只能每次减一来找。
Last updated