Leetcode 492. Construct the Rectangle
Given an area area
, design a rectangular web page, whose length L
and width W
satisfy the following requirements:
W
should not be larger than the length L
, meaning L >= W
.L
and W
should be as small as possible.Return an array [L, W]
where L
and W
are the length and width of the rectangle.
(L, W)
such that L * W = area
and L >= W
?
To solve this problem, we need to find two integers L
and W
such that L * W = area
, L >= W
, and the difference (L - W)
is minimized.
Steps:
W
found, calculate L
as L = area / W
.(L, W)
and return it as soon as we find a valid pair, since we are moving downwards from the square root, this ensures that (L - W)
is minimized.The reason for iterating from the square root downwards is that the factors closest to the square root will have the smallest difference.
#include <cmath>
#include <vector>
#include <iostream>
std::vector<int> constructRectangle(int area) {
int w = static_cast<int>(std::sqrt(area));
while (area % w != 0) {
w--;
}
int l = area / w;
return {l, w};
}
int main() {
int area = 4;
std::vector<int> result = constructRectangle(area);
std::cout << "Length: " << result[0] << ", Width: " << result[1] << std::endl;
return 0;
}
n
is the area. This is because in the worst case, we iterate from the integer part of the square root of area
down to 1 to find the first factor.This solution provides a balanced, minimal and efficient way to find the desired dimensions for the rectangle.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?