https://programmers.co.kr/learn/courses/30/lessons/42576
import java.util.HashMap;
import java.util.Iterator;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String,Integer> hashMap = new HashMap<>();
// participant 추가
for(int i=0;i<participant.length;i++){
if(hashMap.containsKey(participant[i])){
hashMap.replace(participant[i], hashMap.get(participant[i])+1);
}else{
hashMap.put(participant[i], 1);
}
}
// completion 빼기
for(int i=0;i<completion.length;i++){
if(hashMap.containsKey(completion[i])){
if(hashMap.get(completion[i])==1){
hashMap.remove(completion[i]);
}else{
hashMap.replace(completion[i], hashMap.get(completion[i])-1);
}
}
}
Iterator iterator = hashMap.keySet().iterator();
while(iterator.hasNext()){
answer = iterator.next().toString();
}
return answer;
}
}
import java.util.HashMap;
import java.util.Iterator;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String,Integer> hashMap = new HashMap<>();
// participant 추가
for(String p : participant){
hashMap.put(p, hashMap.getOrDefault(p, 0)+1);
}
// completion 빼기
for(String c: completion){
hashMap.put(c, hashMap.get(c)-1);
}
for(String key: hashMap.keySet()){
if(hashMap.get(key)!=0){
answer = key;
}
}
return answer;
}
}
getOrDefault()를 사용했더니 한결 간결해졌다. Map을 사용할 때는 getOrDefault를 잘 사용해야겠다.