Leetcode 492. Construct the Rectangle
The problem is to find a pair of integers (L, W) such that:
L * W = areaL >= WL and W is minimal.Given an integer area, you need to output the pair (L, W).
area?
L and W be equal?
L can be equal to W (especially in case of perfect squares).L and W to be integers?
L and W should be integers.To solve this problem:
L and W to be as close as possible, start checking from the square root of area. This approach ensures that the values of L and W are close.W that divides the area perfectly.W, compute L as area / W.(L, W) where L is always equal to or greater than W.O(sqrt(area)) as we iterate from sqrt(area) down to 1.public class ConstructRectangle {
public int[] constructRectangle(int area) {
// Start from the square root of the area
int W = (int) Math.sqrt(area);
// Iterate downwards to find the width that divides the area perfectly
while (area % W != 0) {
W--;
}
// Compute L and return the results
int L = area / W;
return new int[] {L, W};
}
public static void main(String[] args) {
ConstructRectangle cr = new ConstructRectangle();
// Example usage:
int[] result = cr.constructRectangle(122122);
System.out.println("L = " + result[0] + ", W = " + result[1]);
}
}
Initial Step: Compute the integer value of square root of area.
area (area % W == 0), then it can be considered as W.Calculate L: Divide area by W to get L.
This method ensures that the pair (L, W) you find is the closest possible dimensions that could form the given area.
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?