수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.
마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요
- 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
- completion의 길이는 participant의 길이보다 1 작습니다.
- 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
- 참가자 중에는 동명이인이 있을 수 있습니다.
1. 배열 정렬
// hash관련 문제라는걸 인지 못하고 처음 풀었다.
// 시간복잡도 : O(n)(단순탐색) => O(nLogN) ~ O(n^2)로 증가
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
Arrays.sort(participant);
Arrays.sort(completion);
// 중복체크
for(int i=0; i<completion.length; i++){
if( !participant[i].equals(completion[i]) ){
return participant[i];
}
}
// 참가자 - 완주자 비교 시 불일치의 가장 마지막 선수 리턴
return participant[participant.length - 1];
}
}
2. 해쉬
// 아래는 HashMap을 이용한 풀이이다.
// 참가자를 map에 담되 value=1을 삽입한다.
// 이후 중복되는 데이터가 있다면 get()으로 value값에 +1을 해주며 '동명이인' 처리를 수행한다.
// 추후 완료자수만큼 value값에 -1처리를 해주며, 값이 1이상인 데이터는 미완주자로 간주한다.
// 이후 entrySet으로 반복문을돌려 이름 뽑아내주면 마무리.
import java.util.*;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String, Integer> hmap = new HashMap();
for(int i=0;i<participant.length; i++){
if(hmap.containsKey(participant[i])){
hmap.put(participant[i], hmap.get(participant[i])+1);
}else{
hmap.put(participant[i], 1);
}
}
System.out.println("참가자 리스트 : "+ hmap);
for(int i=0; i<completion.length; i++){
if(hmap.containsKey(completion[i])){
hmap.put(completion[i], hmap.get(completion[i])-1);
}
}
System.out.println("소거 후 리스트 : "+ hmap);
for(Map.Entry<String, Integer> entry : hmap.entrySet()){
System.out.println(entry.getKey() + "/" + entry.getValue());
if( entry.getValue() != 0 ){
answer = entry.getKey();
}
}
return answer;
}
}
▶ 레퍼런스
https://baekh-93.tistory.com/8
[Java 개념정리] HashMap 관련함수
HashMap이란 Map인터페이스의 한종류로써 Key와 Value 값으로 데이터를 저장하는 형태를 가지고 있다. 예를들면 사전처럼 "people" = "사람", "baseball" = "야구" 이런식으로 Key와 value로 대응관계를 쉽게 표
baekh-93.tistory.com
HashMap 반복문 조회
HashMap을 반복문을 통해 조회하는 방법을 확인한다. 대부분 keySet을 사용하여 조회하지만, Map에서 Key에 해당하는 값을 조회하는 비용이 추가로 발생하므로, 왠만하면 entrySet 사용을 추천한다. HashM
lovon.tistory.com
[ 프로그래머스 ] 모의고사 자바 (Lv1, 완전탐색) (0) | 2024.07.29 |
---|---|
[ 프로그래머스 ] 최소직사각형 자바 (Lv1, 완전탐색) (0) | 2024.07.28 |
[ 프로그래머스 ] 전화번호 목록 (Lv2) (0) | 2024.06.18 |