Notice
Recent Posts
Recent Comments
Link
05-03 04:37
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

<<개발일지>>

[힌트 문제1-5] 개수 세기 본문

코딩테스트

[힌트 문제1-5] 개수 세기

개발하는지호 2023. 9. 19. 21:35

백준 문제 : 10807 (개수 세기)

풀이과정 1

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;

public class Main {
    public static void main(String[] args) throws IOException {
        // Hashtable 생성
        Hashtable<Integer, Integer> counts = new Hashtable<>();
        // BufferedReader 생성
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 입력값 n을 읽어와 정수형 변수 n에 저장
        int n = Integer.parseInt(br.readLine());

        // 정수형 배열 numbers 생성
        int[] numbers = new int[n];

        // 공백으로 구분된 문자열을 입력값으로 받아와서, 배열 number에 저장.
        String[] input = br.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            numbers[i] = Integer.parseInt(input[i]);

        }
        // numbers 배열에 있는 숫자들의 개수를 Hashtable에 저장
        for (int num : numbers) {
            if (counts.containsKey(num)) {
                counts.put(num, counts.get(num) + 1);
            } else {
                counts.put(num, 1);
            }
        }
        // 입력값 target을 읽어와 정수형 변수 target에 저장
        int target = Integer.parseInt(br.readLine());
        // target이 Hashtable에 있다면, Hashtable에 해당 숫자의 개수를  출력
        if (counts.containsKey(target)) {
            int count = counts.get(target);
            System.out.println(count);
        } else {
            // target이 Hashtable에 없다면, "0" 출력
            System.out.println("0");
        }
    }
}

풀이과정2

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;

public class Main {
    public static void main(String[] args) throws IOException {
       //Hashtable을 만든다.
        Hashtable<String, Integer> counts = new Hashtable<>();
        // BufferedReder를 만든다.
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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


        String[] numbers = br.readLine().split(" ");

        for (String a : numbers) {
            if (counts.containsKey(a)) {
                counts.put(a, counts.get(a) + 1);
            } else {
                counts.put(a, 1);
            }
        }
        String target = br.readLine();
        System.out.println(counts.get(target));

    }
}

이 두 개의 풀이과정 차이점은 해시테이블의 값 자료형 차이다.

 

 

BufferedReader 와 Scanner 의 비슷하지만 다른 점을 알게 됨

'코딩테스트' 카테고리의 다른 글

[힌트 문제2-5] 트리  (0) 2023.09.27
[힌트 문제1-4] 비트 연산자  (0) 2023.09.20
[힌트 문제1-3] 스택  (0) 2023.09.19
[힌트 문제1-2]숫자 문자열과 영단어  (0) 2023.09.19
[힌트 문제1-1]짝수는 싫어요  (0) 2023.09.19