코딩테스트

[백준 / 실버4] 1302 : 베스트셀러 (JAVA)

lyndaa 2023. 3. 24. 17:08

문제


풀이 방법

  • HashMap을 사용하여 key 값에는 책 제목, value 값에는 팔린 수를 저장한다.
    •  getOrDefault (Object Key, V defaultValue)
  • (1) 맵에 저장할때마다 key값과 value값을 계속해서 이전의 값과 비교하여 더 큰 value값과 사전순으로 앞선 key값을 따로 저장하여 출력한다.
  • (2) 또는, 최대값만 구하고 해당 최대값을 가진 key값을 리스트에 넣고 정렬하여 첫번째 책 제목을 출력한다.

코드

(1)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int value,max=0;
        Map<String, Integer> map = new HashMap<>();
        String str2 = null;

        for(int i=0; i<n; i++){
            String str=br.readLine();
            value=map.getOrDefault(str,0)+1;
            map.put(str,value);
            if(max<=value){
                if(max==value){
                    if(str2.compareTo(str)>0){
                        str2 = str;
                    }
                }else {
                    max = value;
                    str2 = str;
                }
            }
        }
        System.out.println(str2);
    }
}

(2)

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.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int max=0;
        Map<String, Integer> map = new HashMap<>();
        List<String> list = new ArrayList<>();

        for(int i=0; i<n; i++){
            String str=br.readLine();
            map.put(str,map.getOrDefault(str,0)+1);
            max = Math.max(max,map.get(str));
        }
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            if(entry.getValue()==max) {
                list.add(entry.getKey());
            }
        }
        Collections.sort(list);
        System.out.println(list.get(0));
    }
}