백준 [JAVA] :: 10816번 숫자 카드 2

smi·2023년 2월 21일
0

BAEKJOON (백준)

목록 보기
55/56

📚 문제 정의

숫자 카드는 정수 하나가 적혀져 있는 카드이다. 상근이는 숫자 카드 N개를 가지고 있다. 정수 M개가 주어졌을 때, 이 수가 적혀있는 숫자 카드를 상근이가 몇 개 가지고 있는지 구하는 프로그램을 작성하시오.


📝 입력

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다. 넷째 줄에는 상근이가 몇 개 가지고 있는 숫자 카드인지 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이 수도 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다.

  • 예제 입력 1
10
6 3 2 10 10 10 -10 -10 7 3
8
10 9 -5 2 3 4 5 -10

📝 출력

첫째 줄에 입력으로 주어진 M개의 수에 대해서, 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지를 공백으로 구분해 출력한다.

  • 예제 출력 1
3 0 0 1 2 0 0 2

💡 코드

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        int[] ary = new int[N];

        for(int i = 0; i < N; i++) {
            ary[i] = s.nextInt();
        }

        Arrays.sort(ary);

        int M = s.nextInt();
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < M; i++) {
            int num = s.nextInt();
            sb.append(upperBound(ary, num) - lowerBound(ary, num)).append(' ');
        }
        System.out.println(sb);
    }

    private static int lowerBound(int[] ary, int num) {
        int start = 0;
        int end = ary.length;

        while (start < end) {
            int mid = (start + end) / 2;

            if (num <= ary[mid]) end = mid;
            else start = mid + 1;
        }
        return start;
    }

    private static int upperBound(int[] ary, int num) {
        int start = 0;
        int end = ary.length;

        while (start < end) {
            int mid = (start + end) / 2;

            if (num < ary[mid]) end = mid;
            else start = mid + 1;
        }
        return start;
    }
}

💡 다른 방법

위의 방법보다 메모리와 시간이 둘 다 적다는 장점이 있다.

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int[] counting = new int[20000001];
        
        int N = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine(), " ");

        for(int i = 0 ; i < N; i++) {
            counting[Integer.parseInt(st.nextToken()) + 10000000]++;
        }

        int M = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine(), " ");

        for(int i = 0; i < M; i++) {
            sb.append(counting[Integer.parseInt(st.nextToken()) + 10000000]).append(' ');
        }
        
        System.out.println(sb);
    }
}
profile
공부한 거 올려요 :)

0개의 댓글