解题思路:
第一种方法是双重for循环的方法,可以理解为枚举,长从最长(即面积)开始往小遍历,宽从1开始往L走,不断寻找最接近的长宽,最好返回即可,代码如下:
class Solution {
public:
vector<int> constructRectangle(int area) {
vector<int> res(2);
for(int i = area; i >= sqrt(area); i --) {
for(int j = 1; j <= i; j ++) {
if(i * j > area) {
break;
}
if(i * j == area) {
res[0] = i;
res[1] = j;
}
}
}
return res;
}
};
第二种方法就更为简单了,这是一种数学的方法, 因为我们知道面积一定能整除,从面积的平方根开始往下找,找到能整除的就是宽,剩下的就是长,代码如下:
class Solution {
public:
vector<int> constructRectangle(int area) {
int width = sqrt(area);
while(area % width) {
width --;
}
return {area / width, width};
}
};