LeetCode 492: Construct the Rectangle
Problem Description
Explanation
To solve this problem, we need to find the dimensions of a rectangle with a given area such that the difference between the length and width is minimized. We can start by iterating from the square root of the given area down to 1 and checking if the current number is a valid width for the given area. If we find a valid width, we can calculate the corresponding length and return the result.
- Start iterating from the square root of the given area down to 1
- Check if the current number is a valid width by dividing the area by the current number and checking if the remainder is 0
- If a valid width is found, calculate the length and return the result
Time complexity: O(sqrt(area)) Space complexity: O(1)
Solutions
class Solution {
public int[] constructRectangle(int area) {
int width = (int) Math.sqrt(area);
while (area % width != 0) {
width--;
}
return new int[]{area / width, width};
}
}
Related LeetCode Problems
Loading editor...