728x90
※ 문제
1) 실패코드
이 코드는 여러번의 삽질 끝에 원인을 발견해서 작성한다. 방식은 '브루드 포스 알고리즘'으로 풀었고 예제 문제도 모두 맞추었으나 제출 시 '틀렸습니다.'가 반환되었다. 고민 끝에 반례는 중복 코드인 경우가 생각났다. 자세히 설명하자면 HashMap은 key값이 동일한 경우 add가 되지 않고 set이 되기 때문에 중복이슈가 발생하여 틀린 것이었다.
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static HashMap<Integer, Integer> xMap = new HashMap<>();
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
int[] compare = new int[count];
for(int i=0; i<count; i++) {
int[] arr = new int[2];
arr[0] = scan.nextInt();
arr[1] = scan.nextInt();
compare[i] = arr[0];
xMap.put(arr[0], arr[1]);
}
for(int i=0; i<count; i++) {
int rank = 1;
for(int j=0; j<count; j++) {
if(i == j) continue;
if(compare[i] < compare[j] && (xMap.get(compare[i]) < xMap.get(compare[j]))) {
rank++;
}
}
System.out.print(rank+" ");
}
}
}
※ 반례 ※ 기대값 ※ 결과값
3 - 2 1 1 - 1 1 1
55 185
55 190
88 186
2) 성공코드
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
int[] compare = new int[count];
int[] compare2 = new int[count];
for(int i=0; i<count; i++) {
compare[i] = scan.nextInt();
compare2[i] = scan.nextInt();
}
for(int i=0; i<count; i++) {
int rank = 1;
for(int j=0; j<count; j++) {
if(i == j) continue;
if( compare[i] < compare[j] && compare2[i] < compare2[j] ) {
rank++;
}
}
System.out.print(rank+" ");
}
}
}
'1) 실패 코드'에서 보완하여 중복이슈가 없는 배열로 처리하였다.
728x90
'자기계발 > 백준 문제 풀이' 카테고리의 다른 글
17298 자바 ] 오큰수(풀이) (0) | 2022.09.09 |
---|---|
1406 자바 ] 에디터(풀이) (0) | 2022.09.01 |
1009 자바 ] 분산처리(풀이) (0) | 2022.09.01 |
10757 자바 ] 큰 수 A+B(풀이) (0) | 2022.09.01 |
11720 자바 ] 숫자의 합 (풀이) (0) | 2022.09.01 |