본문 바로가기

백준 문제풀이

[Baekjoon 11652] 카드 - Java

728x90

[Silver IV] 카드 - 11652

문제 링크

성능 요약

메모리: 32528 KB, 시간: 392 ms

분류

자료 구조, 해시를 사용한 집합과 맵, 정렬

제출 일자

2024년 4월 18일 13:32:51

문제 설명

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

준규가 가지고 있는 카드가 주어졌을 때, 가장 많이 가지고 있는 정수를 구하는 프로그램을 작성하시오. 만약, 가장 많이 가지고 있는 정수가 여러 가지라면, 작은 것을 출력한다.

입력

첫째 줄에 준규가 가지고 있는 숫자 카드의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개 줄에는 숫자 카드에 적혀있는 정수가 주어진다.

출력

첫째 줄에 준규가 가장 많이 가지고 있는 정수를 출력한다.

문제 풀이

해당 문제는 신경써줘야하는게 몇가지 있다.

  1. int형 범위인 (-2,147,483,648 ~ 2,147,483,647)를 넘기기 때문에 Long을 사용해야 한다.
  2. 같은 개수일 경우 "작은" 정수가 우선순위를 가진다.

문제를 풀기위해 몇가지 생각했던게 있다.

  1. TreeMap에 값을 저장하고 Value가 높은것을 찾는 방법

  2. Map에 값을 저장하고 람다식을 사용해 정렬하는 방법

TreeMap을 사용하면 람다식을 사용하지 않고 입력을 다 받은 뒤 가장 많은 개수를 가진 Key를 찾으면 된다.

람다식을 사용할 경우 정렬함과 동시에 compareTo를 사용해서 값을 비교해주면 된다.

  • TreeMap을 사용한 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

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 maxValue = 0; // 최대 Value를 저장할 변수
        Long maxKey = 0L; // 최대 Key를 저장할 변수

        TreeMap<Long, Integer> map = new TreeMap<>();

        while (n -- > 0){
            long input = Long.parseLong(br.readLine());
            map.put(input, map.getOrDefault(input, 0) + 1);
        }


        for (Map.Entry<Long, Integer> entry : map.entrySet()) {
            int currentValue = entry.getValue();
            if (currentValue > maxValue) {
                maxValue = currentValue;
                maxKey = entry.getKey();
            }
        }

        System.out.println(maxKey);
    }
}
  • 람다식을 사용한 풀이
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());
        Map<Long, Integer> map = new HashMap<>();
        while (n-->0){
            long input = Long.parseLong(br.readLine());
            map.put(input, map.getOrDefault(input, 0) + 1);
        }



        System.out.println(  map.entrySet().stream()
                .sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
                .sorted((e1, e2) -> -e1.getValue().compareTo(e2.getValue()))
                .findFirst().get().getKey());

코드 풀이

int n = Integer.parseInt(br.readLine());

int maxValue = 0;
Long maxKey = 0L;

TreeMap<Long, Integer> map = new TreeMap<>();

while (n -- > 0){
    long input = Long.parseLong(br.readLine());
    map.put(input, map.getOrDefault(input, 0) + 1);
}
  • n: 숫자 카드의 개수를 저장할 변수
  • while (n -- > 0)을 통해 숫자 카드의 개수만큼 입력받는다.
  • input: 입력받을 카드의 숫자
  • 입력받은 input을 바로 map에 넣어준다.
for (Map.Entry<Long, Integer> entry : map.entrySet()) {
    int currentValue = entry.getValue();
    if (currentValue > maxValue) {
        maxValue = currentValue;
        maxKey = entry.getKey();
    }
}
  • map.entrySet()을 사용하여 모든 Value값을 돈다.
  • 만약 현재 Value가 최대 Value보다 클 경우 maxValuemaxKey의 값을 교체해준다.