본문 바로가기
알고리즘/Class 3

백준 BOJ 1764번

by edvedv 2022. 8. 19.


접근 방법

 

N과 M이 500000 이하라서 배열에 저장해서 contains를 하면 시간초과가 나는 문제다.

HashSet을 이용하면 쉽게 해결할 수 있다. 주의할 점은 사전순으로 출력해야 되기 때문에, 정렬하고 출력해야한다.


코드

import java.util.*;

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

      HashSet<String> set = new HashSet<>();
      for(int i = 0; i < n; i++)
         set.add(in.next());
      
      ArrayList<String> answer = new ArrayList<>();
      for(int i = 0; i < m; i++){
         String temp = in.next();
         if(set.contains(temp)) answer.add(temp);
      }
      Collections.sort(answer);

      System.out.println(answer.size());
      for(int i = 0; i < answer.size(); i++){
         System.out.println(answer.get(i));
      }
   }
}

'알고리즘 > Class 3' 카테고리의 다른 글

백준 BOJ 1927번  (0) 2022.08.21
백준 BOJ 1780번  (0) 2022.08.20
백준 BOJ 1697번  (0) 2022.08.19
백준 BOJ 1676번  (0) 2022.08.19
백준 BOJ 1620번  (0) 2022.08.18

댓글