Notice
Recent Posts
Recent Comments
Link
개발 공부~
[백준 - 1302] 베스트셀러 .java 본문
https://www.acmicpc.net/problem/1302
내 풀이
- 입력받은 수만큼 카운트 -> 책 이름과 팔린 개수를 쌍으로 저장하는 자료구조
- 많이 팔린 책이 여러 개라면 사전순으로 가장 앞서는 제목을 출력 -> 순서 보장
=> TreeMap 사용, 대신 value값으로 정렬할 수는 없으므로 객체로 묶은 set로 접근
-> 이미 순서는 보장되어있기 때문에 같은 수일땐 가장 앞서는 이름이 정답
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<String, Integer> map = new TreeMap<>();
while(n-->0){
String name = sc.next();
map.put(name, map.getOrDefault(name, 0) + 1);
}
int max = 0;
String answer = "";
for(Map.Entry<String, Integer> entry : map.entrySet()){
if(max<entry.getValue()){
max = entry.getValue();
answer = entry.getKey();
}
}
System.out.println(answer);
}
}
다른 풀이 - 배열 정렬
입력받은 책 제목 배열을 정렬한 뒤 다음 책과 현재 책 제목이 같으면 카운트를 증가시킨다
그렇게 센 카운트 중에서 가장 큰 값을 구하면 된다
import java.util.Arrays;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] titles = new String[n];
for(int i = 0; i < n; i++) {
titles[i] = sc.next();
}
Arrays.sort(titles);
int maxCount = 1;
//0번 인덱스부터 시작 -> 카운트 1이 기본값
int cur = 1;
String maxTitle = titles[0];
for(int i =1;i <n;i++){
if(!titles[i].equals(titles[i-1])){
cur = 0;
}
cur++;//다르더라도 현재는 카운트 해야함
if(cur > maxCount ){
maxCount = cur;
maxTitle = titles[i];
}
}
System.out.println(maxTitle);
}
}
'코딩테스트 > 백준' 카테고리의 다른 글
[백준 - 2910] 빈도 정렬 .java (0) | 2025.05.13 |
---|---|
[백준 - 18870] 좌표 압축 .java (0) | 2025.05.13 |
[백준 - 7785] 회사에 있는 사람 .java (1) | 2025.05.08 |
[백준 - 10814] 나이순 정렬 .java (1) | 2025.05.08 |
[백준-1110] 더하기 사이클 .java (0) | 2025.05.07 |