공부/백준

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

빈v 2022. 6. 1. 19:14
728x90

https://www.acmicpc.net/problem/10816

 

10816번: 숫자 카드 2

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

www.acmicpc.net

 

https://binsblog.tistory.com/33

 

[백준-10815] 숫자 카드 - Java

https://www.acmicpc.net/problem/10815 10815번: 숫자 카드 첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드..

binsblog.tistory.com

위와 비슷한 유형이다.

위에서는 HashSet을 이용하였고, 이 문제에서는 HashMap을 이용하였다.

번호가 몇번 나왔는지 HashMap에 저장을 하고, 있는지 없는지에 따라 value 혹은 0을 문자열에 추가해 주었다.

처음에는 for문안에 바로 print문을 추가하여 출력하려 했지만, 시간초과로 인해 StringBuilder를 사용하였다. 

 

코드

import java.util.*;
public class back10816 {
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int num=scanner.nextInt();
        HashMap<Integer,Integer> map = new HashMap<>();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<num;i++){
            int temp=scanner.nextInt();
            if(map.containsKey(temp)){
                map.put(temp,map.get(temp)+1);
            }else{
                map.put(temp, 1);
            }            
        }
        num=scanner.nextInt();
        for(int i=0;i<num;i++){
            int temp=scanner.nextInt();
            if(map.containsKey(temp)){
                sb.append(map.get(temp)).append(" ");
            } else{
                sb.append("0 ");
            }
        }
        System.out.println(sb);
       
    }
}
728x90
반응형