1. 완주하지 못한 선수
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
Map<String,Integer> map = new HashMap<>();
for(String values: participant){
map.putIfAbsent(values,0);
map.put(values,map.get(values)+1);
}
for(String values: completion){
map.put(values,map.get(values)-1);
}
for(String keys : map.keySet()){
if(map.get(keys) == 1){
return keys;
}
}
return answer;
}
}
Map을 활용하면, 쉽게 배열에 담긴 값의 갯수를 셀 수 있고
두 개의 배열을 쉽게 비교할 수 있다.
2. 전화번호 목록
import java.util.*;
class Solution {
public boolean solution(String[] phone_book) {
boolean answer = true;
for(int i=0; i<phone_book.length; i++){
for(int j=i+1; j<phone_book.length; j++){
if(phone_book[j].startsWith(phone_book[i])){
return false;
}else if(phone_book[i].startsWith(phone_book[j])){
return false;
}
}
}
return answer;
}
}
startWith를 처음 사용 해봐서 해시를 이용하지 않고 작성해보았다.
import java.util.*;
class Solution {
boolean answer = true;
public boolean solution(String[] phone_book) {
int min=Integer.MAX_VALUE;
HashMap<String,Integer> resultHash = new HashMap();
for(int i=0; i<phone_book.length; i++) {
min = Math.min(min, phone_book[i].length());
}
for(int i=0; i<phone_book.length;i++) {
String headerText = phone_book[i].substring(0,min);
resultHash.putIfAbsent(headerText,0);
resultHash.put(headerText,resultHash.get(headerText)+1);
}
resultHash.forEach((key,value)->{
if(value>1) {
answer = false;
}
});
return answer;
}
}
일단 배열에서 제일 작은 값을 찾고
그 크기만큼만 substring메소드를 활용하여 문자열을 뽑아낸다.
뽑아낸 문자열은 Map에 하나씩 쌓아올린다.
쌓아올린 Map에서
foreach 와 람다식을 활용하여
중복된 값이 있을 시에
answer을 false값으로 바꾼다.
3. 위장
import java.util.*;
class Solution {
int answer = 1;
public int solution(String[][] clothes) {
Map<String,Integer> map = new HashMap<>();
for(String[] value : clothes){
map.putIfAbsent(value[1],0);
map.put(value[1],map.get(value[1])+1);
}
map.forEach((key,value)->{
answer = answer*(value+1);
});
return answer-1;
}
}
경우의 수를 따지기 위해 조합(순열)을 이용하여 따졌다.
n = (q+1) * (w+1) * (e+1) .. -1
'Algorithm' 카테고리의 다른 글
[힙(Heap)] 더 맵게, 라면 공장, 이중 우선순위 큐 (0) | 2019.07.05 |
---|---|
[Hash] Map(STL Container) 이해하기 (완주하지 못한 선수, 위장) (0) | 2019.07.05 |
[정렬2] ABC, 수열 정렬, 전화번호부 목록,거북이 (0) | 2019.07.04 |
[DFS] DFS/DFS, 타겟넘버, 네트워크, 단어변환 (0) | 2019.07.04 |
[정렬] K번째 수, 가장 큰 수, H-Index, 수 정렬하기, 나이순 정렬, 단어 정렬 (0) | 2019.07.03 |