Post

[Programmers] #120860 - 직사각형 넓이 구하기 [Java][C++][Python]

[Programmers] #120860 - 직사각형 넓이 구하기 [Java][C++][Python]

문제 링크


1. 아이디어

2차원 좌표 평면에 변이 축과 평행한 직사각형이 있으며 각 꼭짓점의 좌표가 주어질 때 직사각형의 넓이를 반환하는 문제다. 직사각형의 넓이는 가로 길이와 세로 길이의 곱으로 가로 길이는 두 x좌표의 차로, 세로 길이는 두 y좌표의 차로 구하면 된다.


2. 복잡도

접근시간공간
풀이$O(1)$$O(1)$

3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
class Solution {
    public int solution(int[][] dots) {
        int minx = Math.min(Math.min(dots[0][0], dots[1][0]), Math.min(dots[2][0], dots[3][0]));
        int maxx = Math.max(Math.max(dots[0][0], dots[1][0]), Math.max(dots[2][0], dots[3][0]));
        int miny = Math.min(Math.min(dots[0][1], dots[1][1]), Math.min(dots[2][1], dots[3][1]));
        int maxy = Math.max(Math.max(dots[0][1], dots[1][1]), Math.max(dots[2][1], dots[3][1]));
        return (maxx - minx) * (maxy - miny);
    }
}
1
2
3
4
5
6
7
8
9
10
#include <bits/stdc++.h>
using namespace std;

int solution(vector<vector<int>> dots) {
    int minx = min({dots[0][0], dots[1][0], dots[2][0], dots[3][0]});
    int maxx = max({dots[0][0], dots[1][0], dots[2][0], dots[3][0]});
    int miny = min({dots[0][1], dots[1][1], dots[2][1], dots[3][1]});
    int maxy = max({dots[0][1], dots[1][1], dots[2][1], dots[3][1]});
    return (maxx - minx) * (maxy - miny);
}
1
2
3
def solution(dots):
    xs, ys = zip(*dots)
    return (max(xs) - min(xs)) * (max(ys) - min(ys))

zip(*dots)는 네 점을 각각 인자로 풀어 zip에 넘겨 x좌표끼리 xs로, y좌표끼리 ys로 묶을 수 있는 점을 활용했다.


This post is licensed under CC BY 4.0 by the author.