프로그래머스 알고리즘

bebrain·2023년 3월 16일
0

내가 쓴 코드

function chunk(data = [], size = 1) {
    const arr = [];

    for (let i = 0; i < data.length; i += size) {
        arr.push(data.slice(i, i + size));
    }
    return arr;
}

function solution() = {
    const targetArr = [];
    const result = [];
    const answer = [];
    const final = [];

    targets.forEach((ele) => targetArr.push(...ele.split("")));
    for (let i in targetArr) {
        const inspect0 = keymap[0]?.includes(targetArr[i]);
        const inspect1 = keymap[1]?.includes(targetArr[i]);
        const index0 = keymap[0]?.indexOf(targetArr[i]);
        const index1 = keymap[1]?.indexOf(targetArr[i]);

        if (inspect0 && inspect1) {
            result.push(Math.min(index0, index1));
        } else if (inspect0) {
            result.push(index0);
        } else if (inspect1) {
            result.push(index1);
        } else {
            result.push(-1);
        }
    }

    for (let i in result) {
        if (result[i] !== -1) {
            result[i] = result[i] + 1;
        }
    }

    const a = chunk(result, result.length / targets.length);

    answer.push(...a);

    for (let i in answer) {
        const sum = answer[i].reduce((a, b) => a + b);
        if (answer[i].includes(-1)) {
            final.push(-1);
        } else {
            final.push(sum);
        }
    }
    return final;
};

정답코드

function solution(keymap, targets) {
    const answer = [];
    const map = {}
    for (const items of keymap) {
        items.split('').map((item, index) => map[item] = (map[item] < index+1 ? map[item] : index+1))
    }
    for (const items of targets) {
        answer.push(items.split('').reduce((cur, item) => cur += map[item], 0) || -1)
    }
    return answer;
}

오늘 새롭게 알게 된 사실.

알고리즘문제에서 이중for문을 쓴 경우 자칫 타임오버로 실패로 처리될 수도 있다.

이중for문은 시간복잡도가 N²으로 데이터가 많아질수록 처리시간이 급수적으로 늘어나는 알고리즘이기 때문에 지양해야 한다.

이중for문을 쓰면 코드가 훨씬 줄어들어 보기에는 좋아 보이지만 보기에만 좋다.

갈 길이 멀다.

0개의 댓글