프로그래머스 - 겹치는 선분의 길이

이윤주·2023년 7월 17일

코딩테스트

목록 보기
17/18

출처
프로그래머스 - 겹치는 선분의 길이

ex)

toppingresult
[[0, 1], [2, 5], [3, 9]]2
[[-1, 1], [1, 3], [3, 9]]0
[[0, 5], [3, 9], [1, 10]]8
function solution(lines) {
    let count = 0;
    let allLines = []; // 총 끈 길이
    const startLine = Math.min(...lines.flat())  // 0
    const endLine = Math.max(...lines.flat())  // 9
    
    for(let i = startLine ; i <= endLine ; i++) { // 10개 
      allLines.push({line: i, count: -1}) // 한번은 겹치므로 count -1 설정 
    }
    
    
    lines.forEach(([start, end]) => {
      // 
        let min= 0;
        let max= 0;
        
        for(const i in allLines) {
        // i(선이 start, end와 같다면, min max에 추가)
            if(allLines[i].line === start) min = Number(i);
            if(allLines[i].line === end) max = Number(i);
        }
      // min, nax만큰 선에 count
        for(let i = min + 1; i <= max; i++) {
            allLines[i].count += 1
        }
    
    
    })
    // count가 0 이상(2번이상 겹쳐있다면 count);
    allLines.forEach(
      (line) => {
        if(line.count > 0) count++}
      )
    
    return count
}

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

정말 잘 읽었습니다, 고맙습니다!

답글 달기