알고리즘/이분탐색

[백준] 10816 숫자카드 2 #Java

VIPeveloper 2022. 5. 7. 13:34
728x90
반응형
package com.company;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;


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 [] arr = new int[n];

        StringTokenizer st = new StringTokenizer(br.readLine()," ");

        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(arr);

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

        st = new StringTokenizer(br.readLine()," ");
        StringBuilder sb = new StringBuilder();


        for (int i = 0; i < m; i++) {
            int key = Integer.parseInt(st.nextToken());
            sb.append(upper_bound(arr, key) - under_bound(arr, key)).append(' ');
        }
        System.out.println(sb);
    }

    public static int under_bound(int [] arr,int key){
        int lo = 0;
        int hi = arr.length;

        while (lo < hi){
            int mid = (lo + hi) / 2;

            if(key <= arr[mid]){
                hi = mid;
            }else{
                lo = mid + 1;
            }
        }
        return lo;
    }
    public static int upper_bound(int[] arr , int key){
        int lo = 0;
        int hi = arr.length;

        while (lo < hi){
            int mid = (lo + hi) / 2;

            if(key < arr[mid]){
                hi = mid;
            }else{
                lo = mid + 1;
            }
        }
        return lo;
    }
}
728x90
반응형

'알고리즘 > 이분탐색' 카테고리의 다른 글

[백준] 2805번 나무 자르기 #Java  (0) 2022.05.09
[백준] 1654번 : 랜선 자르기 #Java  (0) 2022.05.08