본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 836. Rectangle Overlap

반응형

https://leetcode.com/problems/rectangle-overlap/description/

 

Rectangle Overlap - LeetCode

Can you solve this real interview question? Rectangle Overlap - An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top

leetcode.com

분기문을 사용해보는 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 구조체로 직사각형 Rect를 정의합니다. 각 직사각형의 좌하, 우상 좌표를 의미하는 struct Point를 정의합니다.2. rec1, rec2 에서 좌표를 Rect변수 r1, r2에 저장해줍니다.

📔 풀이과정

4가지 경우에 있어서 하나라도 해당된다면 false를 반환해줍니다.

1. r1의 좌하 x좌표가 r2의 우상 x좌표 이상인 경우

2. r1좌하 y좌표가 r2우상 y좌표 이상인 경우

3. r1우상 x좌표가 r2좌하 x좌표 이하인 경우

4. r1우상 y좌표가 r2좌하 y좌표 이하인 경우

📔 정답 출력 | 반환

경우에 따라 정답을 반환합니다.


📕 Code

📔 C++

struct Point {
    int x,y;
};

struct Rect{
    Point LeftBottom, RightTop;
};

class Solution {
public:
    bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
        Rect r1 = {rec1[0], rec1[1], rec1[2], rec1[3]};
        Rect r2 = {rec2[0], rec2[1], rec2[2], rec2[3]};
        if(r1.LeftBottom.x >= r2.RightTop.x) return false;
        if(r1.LeftBottom.y >= r2.RightTop.y) return false;
        if(r1.RightTop.x <= r2.LeftBottom.x) return false;
        if(r1.RightTop.y <= r2.LeftBottom.y) return false;
        return true;
    }
};

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