본문 바로가기
알고리즘 문제풀이 입문: 코딩테스트 대비/섹션 4. HashMap, TreeSet (해쉬, 정렬지원 Set)

학급 회장 (해쉬)

by _비니_ 2024. 4. 2.

 

해쉬 개념 자체를 까먹어서 처음에는 배열을 사용해 각 후보의 표 수를 직접 계산하는 방법으로 풀었다가

유튜브와 인프런 강의로 해쉬 기본 개념에 대해 다시 공부한 후 강사님이 푼 방식과 유사하게 풀었다.

 

문제 이해

 

각 후보들의 기호가 나열되어있고, 이 중 가장 많은 투표를 받은 기호를 출력하면 되는 문제이다.

 

문제 해결

 

 

스캐너 객체로 학생수 N과 투표 votes를 입력받아줬다. 최종적으로 출력될 학급 회장 classPresident를 char 데이터형태로 만들어주었다.

Scanner in = new Scanner(System.in);

int N = in.nextInt();
in.nextLine();
String votes = in.nextLine();

char classPresident = ' ';

 

후보들 기호의 데이터형은 Character이고, 이들의 투표 수의 데이터형은 Integer이므로 다음과 같은 HashMap을 만들어줄 수 있다.

HashMap<Character, Integer> map = new HashMap<>();

 

 

입력받은 votes는 String이므로 toCharArray() 과정이 필요하다. char 데이터 타입 key로 하나씩 받아 key가 존재하면 key의 값을, 없으면 0을 return 하고 그 값에서 1을 더해 map에 넣어준다. 즉 해당 기호(key)가 들어올 때마다  투표수(value)가 증가되는 코드이다.

for(char key :  votes.toCharArray()){
    map.put(key, map.getOrDefault(key,0) +1); //key가 존재하면 key의 값을, 없으면 0을 return하고 1을 더해서 map에 put
}

 

 

key에 대한 value를 모두 저장했으니 최대값을 찾아 출력하면 된다.

max 변수를 0으로 초기화시켜준 후, value를 max 변수와 비교해 갱신 시켜주면서, value가 가장 클 때 해당하는 key값, 즉 기호를 classPresident 변수에 넣어준 후 출력해주면 된다.

int max = 0;
for(char key : map.keySet()){
    if(map.get(key) > max){ //값을 비교해서
        max = map.get(key);
        classPresident = key; //classPresident에 넣어주는 건 key
    }
}
System.out.println(classPresident);

 

 

최종 코드

 

import java.util.HashMap;
import java.util.Scanner;

public class P01_학급회장_해쉬 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int N = in.nextInt();
        in.nextLine();
        String votes = in.nextLine();

        char classPresident = ' ';

        HashMap<Character, Integer> map = new HashMap<>();
        for(char key :  votes.toCharArray()){
            map.put(key, map.getOrDefault(key,0) +1); //key가 존재하면 key의 값을, 없으면 0을 return하고 1을 더해서 map에 put
        }

        int max = 0;
        for(char key : map.keySet()){
            if(map.get(key) > max){ //값을 비교해서
                max = map.get(key);
                classPresident = key; //classPresident에 넣어주는 건 key
            }
        }
        System.out.println(classPresident);

    }
}
반응형