백준 베스트셀러 1302번(Python, Java)
https://www.acmicpc.net/problem/1302
1302번: 베스트셀러
첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고, 알파벳 소문자로만 이루어져 있다.
www.acmicpc.net
문제를 보자마자 이건 쉬울 것 같은데? 라고 생각했지만 쉽지 않았던 문제이다. ㅜㅠ 결국 풀지 못했다.
뭔가 알겠는데 파이썬과 자바가 살짝 어색해서 그런가 구현이 쉽게 되지 않았다.
1. 베스트 셀러 with Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
books = {}
for _ in range(int(input())):
book = input()
if book in books.keys():
books[book] += 1
else:
books[book] = 1
lst=[]
for key in books.keys():
if books[key] == max(books.values()):
lst.append(key)
lst=sorted(lst)
print(lst[0])
|
books 라는 dictionary형으로 만들어서 key, value 를 이용해서 문제를 풀었다. 문제를 풀면서 파이썬에 대해서 새롭게 알게된 부분도 많은데 그게 바로 sorted 였다. sorted는 리스트를 정렬을 한 후에 새로운 리스트로 반환해준다.
이 문제에서 books[key] == max(books.values()) 이 부분이 뭔가 쉽게 떠오르지 않았던 부분이다.
2. 베스트셀러 with Java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class BestSeller {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
HashMap<String,Integer> hm = new HashMap<>();
int n = input.nextInt();
for (int i = 0; i < n; ++i) {
String book = input.next();
if (!hm.containsKey(book)) {
hm.put(book, 1);
}
else {
hm.put(book, hm.get(book) + 1);
}
}
int max = 0;
for(String a : hm.keySet()){
max = Math.max(max, hm.get(a));
}
ArrayList<String> list = new ArrayList<>(hm.keySet());
Collections.sort(list);
for (String a : list) {
if (hm.get(a) == max) {
System.out.println(a);
break;
}
}
}
}
|
자바는 확실히 파이썬보다 훨씬 구현이 까다롭다고 느꼈다.. HashMap과 ArrayList를 이용해서 풀었다.
HashMap은 파이썬에서 dictionary 자료형과 같고, ArrayList는 리스트와 같다. 그리고 Collections.sort 는 sorted와 같아서 두 언어가 푼 개념을 똑같다.
다만
ArrayList<String> list = new ArrayList<>(hm.keySet()); 을 하면 굳이 add를 하지 않아도 추가가 된다는 부분은 처음 보는데 이게 어떤 원리로 되는건지 궁금하다.
그래서 ArrayList가 내부적으로 어떻게 구현이 되어있는지 찾아 보니 아래와 같았다.
1
2
3
4
5
6
7
8
9
10
11
12
|
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
|
인자로 Collection<? extends E> c) 라고 되어 있기 때문에 Collection 인터페이스에 상속받은 것들만 가능하다.
예를들면 List, Set, Map 등이 있다.