[ 다먹살 ]/- Coding

[백준] 1302 베스트셀러

엉망으로살기 2021. 10. 25. 17:10
반응형

https://www.acmicpc.net/problem/1302

 

1302번: 베스트셀러

첫째 줄에 오늘 하루 동안 팔린 책의 개수 N이 주어진다. 이 값은 1,000보다 작거나 같은 자연수이다. 둘째부터 N개의 줄에 책의 제목이 입력으로 들어온다. 책의 제목의 길이는 50보다 작거나 같고

www.acmicpc.net

 

해시 맵 구조를 활용해서 해결할 수 있는 문제였다. 해시 맵을 key-value 둘 다 기준으로 잡고 정렬하는 방법은 다른 문제에서도 꽤 많이 사용하는데 IDE없이도 어느 정도 구현할 수 있도록 확실한 연습이 필요할 것 같다.


문제 및 입출력


예제


코드

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        
        // 책 이름을 기준으로 이미 map에 입력되었을 경우 +1, 없을 경우 1로 put
        for(int i=0; i<n; i++)
        {
            String temp = sc.next();
            
            if(map.containsKey(temp))
            {
                map.put(temp, map.get(temp)+1);
            }
            else
            {
                map.put(temp, 1);
            }
        }
        
        ArrayList<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(map.entrySet());
        
        // 각 도서별로 count를 기준으로 정렬하며, count가 같으면 책 이름을 기준으로 정렬
        Collections.sort(list, new Comparator<Entry<String, Integer>>(){
           @Override
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2)
            {
                if(o1.getValue()==o2.getValue())
                {
                    return o2.getKey().compareTo(o1.getKey());
                }
                else
                {
                    return o1.getValue()-o2.getValue();
                }
            }
        });
        
        System.out.println(list.get(list.size()-1).getKey());
    }
}

 

반응형