프로그래머스 LEVEL 1(숫자 짝꿍)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-10-19

  • 해결 방법 :
    • 처음에 X, Y에 중첩된 값을 찾을 때 splice()로 제거하였는데, 시간이 오래 걸리는 문제 발생
    • Map() 자료구조를 활용하여 map_x을 돌며 map_y에 key가 존재할 때 arr에 push()
    • arr이 빈 경우 ‘-1’, arr이 ‘0’으로만 이루어진 경우 ‘0’ 반환
    • 그 외의 경우 내림차순 정렬 후 join() 수행
  • 회고 :
    • x
  • 코드

    function solution(X, Y) {
        const map_x = new Map();
        const map_y = new Map();
        const arr = [];
            
        for (const x of X) {
            map_x.set(x, map_x.has(x) ? map_x.get(x) + 1 : 1);
        }
        for (const y of Y) {
            map_y.set(y, map_y.has(y) ? map_y.get(y) + 1 : 1);
        }
            
        for (const [key, value] of map_x.entries()) {
            if (map_y.has(key)) {
                for (let i = 0; i < Math.min(value, map_y.get(key)); i++) {
                    arr.push(key);
                }
            }
        }
            
        if (!arr.length) return '-1';
        if (arr.every((e) => e === '0')) return '0';
        arr.sort((a, b) => b - a);
            
        return arr.join('');
    }
    
  • 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges