Java/코딩테스트

[java/프로그래머스/120860] 직사각형 넓이 구하기 (Math.abs(), Math.max())

Se On 2025. 2. 4. 14:38

✏️ 문제 설명

2차원 좌표 평면에 변이 축과 평행한 직사각형이 있습니다. 직사각형 네 꼭짓점의 좌표 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]가 담겨있는 배열 dots가 매개변수로 주어질 때, 직사각형의 넓이를 return 하도록 solution 함수를 완성해보세요.


✏️ code - 1차

📌 아쉬운 점
- break 때문에 루프가 중간에 종료되지만, if-else를 두 번 확인해야 해서 코드가 다소 복잡합니다.
import java.lang.Math;

class Solution {
    public int solution(int[][] dots) {
        int x = dots[0][0];
        int y = dots[0][1];
        
        for (int i = 1; i < 4; i++) {
            if (dots[i][0] > x) {
                x = dots[i][0] - x;
                break;
            } else if (x > dots[i][0]) {
                x -= dots[i][0];
                break;
            }
        }
        
        for (int i = 1; i < 4; i++) {
            if (dots[i][1] > y) {
                y = dots[i][1] - y;
                break;
            } else if (y > dots[i][1]) {
                y -= dots[i][1];
                break;
            }
        }
        
        return Math.abs(x*y);
    }
}

 

✏️ code - 2차

📌 반복문 없이 거리 계산
- dots[0]과 나머지 점들의 x 및 y 차이를 한 번에 구합니다. (부호를 없애기 위해 Math.abs() 절대값 사용)
- Math.max()를 활용해 가장 큰 거리 = 즉, 길이를 직접 구합니다.
import java.lang.Math;

class Solution {
    public int solution(int[][] dots) {
    	int x = Math.max(Math.abs(dots[0][0]-dots[1][0]), Math.abs(dots[0][0]-dots[2][0]));
        int y = Math.max(Math.abs(dots[0][1]-dots[1][1]), Math.abs(dots[0][1]-dots[2][1]));
        return x*y;
    }
}
반응형