일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Android
- androidstudio
- bitmap
- BOJ
- Canvas
- CS
- Database
- DBeaver
- DP
- Ecilpse
- Eclipse
- firebase
- git
- github
- GooglePlayServices
- gradle
- IDE
- IntelliJ
- java
- json
- kotlin
- level2
- linux
- mariadb
- MYSQL
- Paint
- permission
- python
- Sorting
- sourcetree
Archives
will come true
[프로그래머스 / Level1] 최소 직사각형 (Java) 본문
728x90
문제
https://programmers.co.kr/learn/courses/30/lessons/86491?language=java
코딩테스트 연습 - 최소직사각형
[[10, 7], [12, 3], [8, 15], [14, 7], [5, 15]] 120 [[14, 4], [19, 6], [6, 16], [18, 7], [7, 11]] 133
programmers.co.kr
풀이
- 모든 명함 크기를 수용할 수 있는 최소 사이즈 구하기
- 명함을 회전하면 가로(W), 세로(H) 길이가 바뀜
- 모든 명함을 긴 길이가 가로 길이로 오도록 회전시킨다는 생각으로 가로(W), 세로(H) 값에서 큰쪽을 가로로, 작은 쪽을 세로로 width, heigth 값과 비교한다. = Math.max(), Math.min() 함수
- 최대 가로 길이(length) * 최대 세로 길이(height)를 곱해서 넓이를 구한다.
코드 (성공)
class solution {
public int solution(int[][] sizes) {
int width = 0, height = 0;
for(int[] size : sizes){
width = Math.max(width, Math.max(size[0], size[1]));
height = Math.max(height, Math.min(size[0], size[1]));
}
return width * height;
}
}
아래와 같이 sizes[i][0] 가 sizes[i][1] 보다 클 경우 두 값의 위치 바꾸는 식으로도 할 수 있으나, 비교 값이 두개이거나 위 문제같이 최대/최소를 구하는 문제에서는 Math.max(), Math.min()을 사용하는 것이 직관적.
if(size[0] < size[1]){
int tmp = size[0];
size[0] = size[1];
size[1] = tmp;
}
728x90
Comments