코딩테스트-알고리즘/프로그래머스

[프로그래머스/Lv.1] 완주하지 못한 선수

닉네임생각즁 2024. 1. 12. 20:58

 

https://school.programmers.co.kr/learn/courses/30/lessons/42576

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        List<String> list = new ArrayList<>();
        
        for(int i=0; i<participant.length; i++) {
            list.add(participant[i]);
        }
        
        for(int i=0; i<completion.length; i++) {
            list.remove(completion[i]);
        }
        answer = list.get(0);
        return answer;
    }
}

 

 

효율성까지 점수를 매기는 문제였다 😨😨😨

 

코드를 작성하면서도 시간이 많이 걸릴거같긴했다 참가자 목록 모두 리스트에 옮겨줬다가 완주한 목록을 돌며 다시 다 빼는과정거치니까,, 참가자가 1명 이상 100,000명 이하인데 완주는 한명 제외하고 나머지 모두가 한다고 하니 리스트에 최대 100,000명을 넣었다가 99,999명을 빼야하면 어마어마하다

그리고 이건 해시 카테고리에 있는 문제라서 아마도 해시로 풀어야 효율성 좋게 풀리는 문제인듯하다

 

알게된것을 정리해보았다

https://fruits2lim.tistory.com/entry/%EC%98%A4%EB%8A%98%EC%9D%98-%EC%9E%90%EB%B0%94-%EB%AC%B8%EB%B2%95-Map-getOrDefault

 

[오늘의 자바 문법] Map - getOrDefault

getOrDefault(Object key, V DefaultValue) - key에 해당하는 value가 있다면 value 출력 - key에 해당하는 value가 없다면 DefaultValue 출력 예를 통해 더 알아보자 import java.util.HashMap; import java.util.Map; public class MapExamp

fruits2lim.tistory.com

 

적용해서 다시 풀었는데

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        int result;
        
        Map<String, Integer> p = new HashMap<>();
        Map<String, Integer> c = new HashMap<>();
        
        for(int i=0; i<participant.length; i++) {
            p.put(participant[i], 1);
        }
        for(int i=0; i<completion.length; i++) {
            c.put(completion[i], 1);
        }
        
        for(String s : p.keySet()) {
            result = c.getOrDefault(s, 0);
            System.out.println(result);
            if(result == 0) {
                answer = s;
            }
        }        
        return answer;
    }
}

 

 

 

 

어디에서 틀렸는지 result값을 찍어보니까

	for(String s : p.keySet()) {
            result = c.getOrDefault(s, 0);
            System.out.println(result);
            if(result == 0) {
                answer = s;
            }
        }

 

동명이인이 있는 경우를 제대로 잡아주지 못하는거였다

mislav 두명 중 한명이 못 들어왔지만 동명이인 mislav이 있긴하니까 result는 1이 되었던것,,

 

.

.

 

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        int result;
        
        Map<String, Integer> p = new HashMap<>();
        Map<String, Integer> c = new HashMap<>();
        
        for(int i=0; i<participant.length; i++) {
            p.put(participant[i], p.getOrDefault(participant[i], 0) + 1);
        }
        for(int i=0; i<completion.length; i++) {
            c.put(completion[i], c.getOrDefault(completion[i], 0) + 1);
        }
        
        for(String key : p.keySet()) {
            if(p.get(key) != c.get(key)) {
                answer = key;
            }
        }        
        return answer;
    }
}

 

 

완전 다르게 생각해야했다

왜 잘못됐는지는 알겠는데 다시 어떻게 바꿔야 정답이 나올지 안떠올라서 고민하느라 시간을 많이 보냈다 맵을 만들면서 value 값을 바꿔줘야했다 테스트케이스도 통과하고 제출하고도 통과통과통과가 떠서 기분이 좋았는데 답이 다 맞으니까 밑에서 갑자기 효율성테스트가 튀어나왔고

 

끝나지 않는 전쟁 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ울고싶었다,,

딱 하나,,,,,,,,,,

 

더 효율성 좋은 방법은 뭘까? 고민했고

keySet()으로 값을 비교하는 과정에서 효율적이지 못하나? 생각이 들어서 방법을 찾아봤다 더 성능좋은 방법이 있어서 배우고 정리했다 

 

https://fruits2lim.tistory.com/entry/%EC%98%A4%EB%8A%98%EC%9D%98-%EC%9E%90%EB%B0%94-%EB%AC%B8%EB%B2%95-MapEntry

 

[오늘의 자바 문법] Map.Entry

효율성테스트를 통과하지 못하면서 또 새로운 것을 공부하게 되었다 https://fruits2lim.tistory.com/entry/%EC%98%A4%EB%8A%98%EC%9D%98-%EC%9E%90%EB%B0%94-%EB%AC%B8%EB%B2%95-Map-getOrDefault [오늘의 자바 문법] Map - getOrDefault

fruits2lim.tistory.com

 

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        int result;
        
        Map<String, Integer> p = new HashMap<>();
        Map<String, Integer> c = new HashMap<>();
        
        for(int i=0; i<participant.length; i++) {
            p.put(participant[i], p.getOrDefault(participant[i], 0) + 1);
        }
        for(int i=0; i<completion.length; i++) {
            c.put(completion[i], c.getOrDefault(completion[i], 0) + 1);
        } 
        
        String key = "";
        Integer value1 = 0;
        Integer value2 = 0;
        for (Map.Entry<String, Integer> pEntry : p.entrySet()) {
            key = pEntry.getKey();
            value1 = pEntry.getValue();
            value2 = c.get(key);
                   
            if(value1 != value2) {
                answer = key;
            }
        }
            
        return answer;
    }
}

 

 

또 아니었다,,,,,,,,,,, 진짜 끝날줄알았는데😦😦😦😦😦😮

이거말고도 정말 다양하게 바꿔봤고 나중엔 찐눈물흘릴뻔했다진짜로

 

제목따라가나보다 나는 완주하지못한선수가 되었다ㅠㅠㅠㅠㅠㅠㅠㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ 

긴 시간 붙잡고 있다보니까 오기가 생겨서 끝까지 관련답안찾고 풀려다가 결국 찾아봤다

 

https://coding-grandpa.tistory.com/entry/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%99%84%EC%A3%BC%ED%95%98%EC%A7%80-%EB%AA%BB%ED%95%9C-%EC%84%A0%EC%88%98-%ED%95%B4%EC%8B%9C-Lv-1

 

[프로그래머스] 완주하지 못한 선수 (해시 Lv. 1) - 자바 Java

0. 동일 유형 문제 [프로그래머스] 완주하지 못한 선수 (해시 Lv. 1) [프로그래머스] 전화번호 목록 (해시 Lv. 2) [프로그래머스] 위장 (해시 Lv. 2) [프로그래머스] 베스트 앨범 (해시 Lv. 3) Youtube 영상으

coding-grandpa.tistory.com

가장 도움이 된 글👍👍👍👍

participant, completion 각각 따로 맵을 만드는거도 효율성이 떨어졌던거같다

배우고 다시 해보았다 ( 진작 보고 배울걸......😥😥😥)

 

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        int result;
        
        Map<String, Integer> map = new HashMap<>();
        
        for(int i=0; i<participant.length; i++) {
            map.put(participant[i], map.getOrDefault(participant[i], 0) + 1);
        }
        for(int i=0; i<completion.length; i++) {
            map.put(completion[i], map.get(completion[i])- 1);
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if(entry.getValue() != 0) {
                answer = entry.getKey();
            }
        }
            
        return answer;
    }
}

 

participant 돌면서 맵 안에 값을 +1씩해서 넣고 completion을 돌때는 반대로 값을 빼주면 들어오지않은사람의 값만 0이 아니게 된다 이 방법으로 동명이인 역시 처리가 된다

동명이인이 3명이고 이 중 3명이 들어오면 3-3=0 / 2명이 들어오면 3-2=1 이렇게 되니까!

 

 

비슷한 문제를 더 풀어보면서 확실히 해시를 익혀야겠다 더불어 효율성있는 코드도!!

한문제한문제에 이렇게 많은 시간을 잡혀있어야하는건가 생각이 들기도하지만 끝까지 풀어보려고 다양하게 찾아보면서 몰랐던 개념도 많이 접하게 되니까 배우는게 많아지긴한다 그래도 시간은 적당히 잡고 해야겠단 생각이 든다,,,,,,,,,,

 

이순간들이 나에게 소중한 시간이 되길 바라며

아무튼 완료!!🙃