题目地址:
https://leetcode.com/problems/construct-the-rectangle/
给定一个矩形的面积 a a a,其长和宽都是整数。求在其长与宽之差最小的情况下的长和宽是多少。
从 ⌊ a ⌋ \lfloor\sqrt a\rfloor ⌊a⌋开始向下枚举到 1 1 1,一旦发现 a a a能整除之的时候,就得到了宽的长度,商就是长的长度。代码如下:
public class Solution {
public int[] constructRectangle(int area) {
int n = (int) Math.sqrt(area);
for (int i = n; i >= 1; i--) {
if (area % i == 0) {
return new int[]{area / i, i};
}
}
return null;
}
}
时间复杂度 O ( a ) O(\sqrt a) O(a),空间 O ( 1 ) O(1) O(1)。