본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 492. Construct the Rectangle

반응형

https://leetcode.com/problems/construct-the-rectangle/description/

 

Construct the Rectangle - LeetCode

Can you solve this real interview question? Construct the Rectangle - 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

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 인수들을 저장할 vector v를 선언해 줍니다.2. 1 ~ area까지의 인수를 vector v에 담아줍니다.

📔 풀이과정

인수가 홀수라면 같은 수로 이루어진 W,L로 area를 구성할 수 있다는 의미입니다. W와 L차이가 제일 적으면서 해당 조건이 만족하려면 가운데 원소 2개를 반환해주면 됩니다.

📔 정답 출력 | 반환

인수가 짝수인지 홀수인지 구별해 적절히 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> constructRectangle(int area) {
        vector <int> v;
        for(int i = 1; i <= area; i++) {
            if(area % i == 0) v.push_back(i);
        }
        int mid = v.size() / 2;
        if(v.size() % 2) {
            return {v[mid], v[mid]};
        }
        return {v[mid], v[mid-1]};
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.