본문 바로가기
Algorithm

[백준 Silver 4] 11652 카드 - Java

by Ray 2021. 12. 25.

문제링크 : https://www.acmicpc.net/problem/11652

 

11652번: 카드

준규는 숫자 카드 N장을 가지고 있다. 숫자 카드에는 정수가 하나 적혀있는데, 적혀있는 수는 -262보다 크거나 같고, 262보다 작거나 같다. 준규가 가지고 있는 카드가 주어졌을 때, 가장 많이 가지

www.acmicpc.net

 

접근 과정 : 

  • 해쉬맵이나 배열을 사용하면 쉽게 풀 수 있다.
  • 해쉬맵에 <Long, Integer> 형태로 저장하면서 카드의 숫자를 세주고
  • 가장 많은 개수의 카드를 갱신시켜주면 된다.
  • 같은 개수일 경우에는, 카드의 숫자가 더 작은 것으로 갱신하고!!

 

소스 코드 및 결과 :

package BOJ;

/* 
    카드
*/

import java.io.*;
import java.util.*;

public class BOJ11652 {

    public static void main(String[] args) throws NumberFormatException, IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        HashMap<Long, Integer> cards = new HashMap<>();

        int max = 0;
        long x = 0;
        for (int i = 0; i < N; i++) {
            long card = Long.parseLong(br.readLine());

            cards.put(card, cards.getOrDefault(card, 0) + 1);

            if (cards.get(card) > max) {
                max = cards.get(card);
                x = card;
            } else if (cards.get(card) == max) {
                x = Math.min(x, card);
            }
        }

        System.out.println(x);

    }
}

 

P.S 

쉬운 문제였다..

사실 밤을 샜더니... 너무 피곤해서 생각이 필요한 문제는 풀 수가 없더라.

머리가 안굴러가아ㅏㅏㅏ