1.문제
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
The area of the rectangular web page you designed must equal to the given target area.
The width W should not be larger than the length L, which means L >= W.
The difference between length L and width W should be as small as possible.
Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.
직사각형 web page의 넓이 값인 area가 주어지고 [L,W] 값은 L >= W 만족해야한다고 할 때 area를 그릴 수 있는 [L,W] 중 L-W의 값이 최솟값인 [L,W] 을 리턴하는 문제이다.
Example 1
Input: area = 4
Output: [2,2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
Exmaple 2
Input: area = 37
Output: [37,1]
Example 3
Input: area = 122122
Output: [427,286]
Constraints:
2.풀이
- area ~ sqrt(area) 사이의 값이 L 이 될 수 있다.
- area / L 의 값이 정수인 경우 array 배열에 [i, area / i] 값을 넣어준다
- array 배열을 반복문을 돌면서 L-W의 값이 최솟값인 경우의 인덱스를 저장한다.
- array배열에서 최솟값 인덱스의 값을 리턴한다.
/**
* @param {number} area
* @return {number[]}
*/
const constructRectangle = function (area) {
const sqrtNum = Math.floor(Math.sqrt(area));
const array = [];
let minDiff = Infinity;
let minDiffIndex = Infinity;
for (let i = area; i >= sqrtNum; i--) {
if (Number.isInteger(area / i) && i >= area / i) {
// i로 area를 나눈 몫이 정수이고 L >= W인 경우 array에 push
array.push([i, area / i]);
}
}
array.forEach((item, index) => {
// L-W 값이 최소값이면 L-W 값을 최솟값으로 갱신하고 해당 인덱스를 저장한다.
if (item[0] - item[1] <= minDiff) {
minDiff = item[0] - item[1];
minDiffIndex = index;
}
});
return array[minDiffIndex];
};
3.결과
