Live Today
[백준] 1302. 베스트셀러 (Java) 본문
반응형
https://www.acmicpc.net/problem/1302
1302번: 베스트셀러
첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고
www.acmicpc.net
💡 HashMap과 PriorityQueue, Sort를 사용해서 해결
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
public class Main {
static int N;
static class Book implements Comparable<Book>{
String name;
int cnt;
public Book(String name, int cnt) {
this.name = name;
this.cnt = cnt;
}
@Override
public int compareTo(Book o) {
return o.cnt - this.cnt; // 가장 많이 팔리 책
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
HashMap<String, Integer> map = new HashMap<>();
N = Integer.parseInt(br.readLine());
for(int i=0;i<N;i++) {
String temp = br.readLine();
if(map.containsKey(temp)) {
int num = map.get(temp);
num++;
map.put(temp, num);
}
else {
map.put(temp, 1);
}
} // input end
PriorityQueue<Book> bookList = new PriorityQueue<>();
for(String s : map.keySet()) {
bookList.add(new Book(s, map.get(s)));
}
// for(String s : book) {
// System.out.println(s + " : " + map.get(s));
// }
// System.out.println("==========");
ArrayList<String> book = new ArrayList<>();
Book temp = bookList.poll();
int maxNum = temp.cnt;
book.add(temp.name);
while(!bookList.isEmpty()) {
Book b = bookList.poll();
if(maxNum == b.cnt) {
book.add(b.name);
}
else if(maxNum > b.cnt) break;
}
Collections.sort(book); // 책 제목 사전 순 정렬
// 가장 많이 팔린 책 제목 출력 (여러 개인 경우, 사전 순으로 가장 앞서는 제목 출력)
System.out.println(book.get(0));
}
}
'알고리즘 > 백준 문제풀이' 카테고리의 다른 글
[백준] 17825. 주사위 윷놀이 (Java) (0) | 2023.06.17 |
---|---|
[백준] 17135. 캐슬디펜스 (Java) (0) | 2023.06.17 |
[백준] 2573. 빙산 (Java) (0) | 2023.06.05 |
[백준] 19237. 어른 상어 (Java) (0) | 2023.03.03 |
[백준] 1181. 단어 정렬 (Java) (0) | 2023.02.12 |