[Lv.0 겹치는 선분의 길이 *****

01수정·2023년 6월 8일
0
post-thumbnail
post-custom-banner

<입문 100문제> Day 22 - dp, 수학, 조건문, 배열

문제



풀이

(1) 3개가 동시에 겹치는 경우를 고려하지 않아서 일부 테스트케이스 실패

function solution(lines) { 
    const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
    
    let first =  range(lines[0][0], lines[0][1], 1);
    let second = range(lines[1][0], lines[1][1], 1);
    let third = range(lines[2][0], lines[2][1], 1);

    let intersection = [];

    intersection.push(first.filter(num => second.includes(num)));
    intersection.push(second.filter(num => third.includes(num)));
    intersection.push(first.filter(num => third.includes(num)));

    let answer = intersection.reduce((acc, nums) => {
        if (nums.length > 0)
            acc += nums.length-1;
        return acc;
    }, 0);

    return answer;
}

(2) 테스트케이스 2,4,6,8 실패

function solution (lines) {
    let answer = 0;
    let space = new Array(100).fill(0);

    for (let i=0; i<lines.length; i++) {
        let left = lines[i][0];
        let right = lines[i][1];

        for (let j=left; j<right; j++) {
            space[j] += 1;
        }
    }

    for (let dot in space) {
        if (space[dot] > 1) {
            answer +=1 ;
        }
    }

    return answer; 
}
function solution (lines) {
    let space = new Array(100).fill(0);

    for (let i=0; i<lines.length; i++) {
        let left = lines[i][0];
        let right = lines[i][1];

        for (let j=left; j<right; j++) {
            space[j] += 1;
        }
    }

    return space.filter(dot => dot > 1).length;
}

(3) -100≤선분허용범위≤100 => 배열의 길이는 200

function solution (lines) {
    let space = new Array(200).fill(0);

    for (let i=0; i<lines.length; i++) {
        let left = lines[i][0];
        let right = lines[i][1];

        for (let j=left; j<right; j++) {
            space[j+100] += 1;
        }
    }

    return space.filter(dot => dot > 1).length;
}

해답

profile
새싹 FE 개발자
post-custom-banner

0개의 댓글