#해시 #HashSet
백준 브론즈3) 아 맞다 마늘
문제에서 중복이 없고, 포함되지 않은 재료를 찾아야 한다고 하니 set이 바로 생각났다.
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));
HashSet<String> hs = new HashSet<>();
int n = Integer.parseInt(br.readLine());
String[] ingredient = br.readLine().split(" ");
String[] realIngredient = br.readLine().split(" ");
for(int i=0; i<n-1; i++) {
hs.add(realIngredient[i]);
}
for(int i=0; i<n; i++) {
if (!hs.contains(ingredient[i])) {
System.out.println(ingredient[i]);
br.close();
return;
}
}
br.close();
}
}
문제를 풀고나니 막상 중복된 데이터도 없으니 꼭 HashSet으로 안풀어도 될 것 같아서 List로도 풀어봤다.
그런데 HashSet보다 메모리를 더 사용했고 시간도 더 오래걸렸다. 왜일까? (아래에 내용이..)
[HashSet] : 14588KB 112ms
[ArrayList] : 14652KB 132ms
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));
int n = Integer.parseInt(br.readLine());
List<String> ingredient = new ArrayList<>(Arrays.asList(br.readLine().split(" ")));
List<String> realIngredient = new ArrayList<>(Arrays.asList(br.readLine().split(" ")));
for(int i=0; i<n; i++) {
if(!realIngredient.contains(ingredient.get(i))) {
System.out.println(ingredient.get(i));
br.close();
return;
}
}
br.close();
}
}
remove()는 HashSet에 지정한 요소가 있으면 제거하고 true를 반환한다.
넣은 재료를 삭제함으로써 탐색을 최적화 할 수 있다.
시간이 더 적게 드는 것을 확인할 수 있었다. 이정도 차이는 미미한가..
[contains()] : 14588KB 112ms
[remove()] : 14608KB 108ms
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));
HashSet<String> hs = new HashSet<>();
int n = Integer.parseInt(br.readLine());
String[] ingredient = br.readLine().split(" ");
String[] realIngredient = br.readLine().split(" ");
for(int i=0; i<n-1; i++) {
hs.add(realIngredient[i]);
}
for(int i=0; i<n; i++) {
if (!hs.remove(ingredient[i])) {
System.out.println(ingredient[i]);
br.close();
return;
}
}
br.close();
}
}