상세 컨텐츠

본문 제목

[ 프로그래머스 ] 완주하지 못한 선수 (Hash Lv1)

코딩테스트/[ 알고리즘 풀이 ]

by glenn93 2024. 6. 3. 16:49

본문

728x90
반응형

문제 설명

수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.

마라톤에 참여한 선수들의 이름이 담긴 배열 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;
    }
}

 

 

 

▶ 레퍼런스

728x90
반응형

관련글 더보기