※ 백준 (Baekjoon)/[Java] 문제 풀이 ( Solve the problems)
[실버4] 1302. 베스트셀러 (Java)
J 크
2023. 8. 13. 23:25
728x90
반응형
https://www.acmicpc.net/problem/1302
1302번: 베스트셀러
첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고
www.acmicpc.net
과음 이슈...
※ 문제를 요약하면 아래와 같습니다.
▶ 하루 동안 팔린 책의 갯수 N이 주어짐
▶ 팔린 책의 갯수를 카운트해서 가장 많이 팔린 베스트 셀러 책을 출력
▶ 팔린 갯수가 동일하면 사전 순으로 가장 앞서는 제목을 출력
▶ 첫줄에 책의 갯수 N, 이후에 N 개만큼의 책 제목 입력
▶ 베스트 셀러 제목 출력
◈ Input - 1
9
table
chair
table
table
lamp
door
lamp
table
chair
◈ Output - 1
table
◈ Input - 2
6
a
a
a
b
b
b
◈ Output - 2
a
◎ 코드 작성 전, 아래와 같이 솔루션을 정리하였습니다.
▶ Hashmap<String, Integer> 형태로 책 제목 key, 팔린 갯수를 value로 저장
▶ 데이터 저장 후 가장 많이 팔린 횟수 Max로 저장
▶ Max값이 동일한 key(책 제목)가 2개 이상시, 사전 순으로 정렬하여 가장 앞에 오는 책 제목 출력
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(bReader.readLine());
Map<String, Integer> mapBooks = new HashMap<>();
for(int i = 0 ; i < N; i++) {
String strTemp = bReader.readLine();
if(mapBooks.get(strTemp) == null)
mapBooks.put(strTemp, 1);
else
mapBooks.put(strTemp, mapBooks.get(strTemp)+1);
}
int nMax =0;
String strBestSeller = null;
for(String strKey : mapBooks.keySet()) {
if(mapBooks.get(strKey) > nMax) {
nMax = mapBooks.get(strKey);
strBestSeller = strKey;
}
}
ArrayList<String> maxList = new ArrayList<>();
for(String strKey : mapBooks.keySet()) {
if(mapBooks.get(strKey) == nMax) {
maxList.add(strKey);
}
}
Collections.sort(maxList);
bWriter.write(maxList.get(0));
bWriter.flush();
bWriter.close();
}
}
읽어주셔서 감사합니다!
Good Luck! (피드백 고맙습니다)