코테/프로그래머스

[프로그래머스/Lv. 0] 겹치는 선분의 길이

imname1am 2023. 2. 14. 12:05
반응형
 

[프로그래머스] 겹치는 선분의 길이 문제 풀이(코딩테스트 입문 Lv. 0) - 자바 Java

0. 자세한 설명은 YouTube 영상으로 1. 배열을 활용한 Solution class Solution { public int solution(int[][] lines) { // 1. arr 배열 및 변수 초기화 int[] arr = new int[200]; int answer = 0; // 2. lines 정보를 arr 배열에 적용 for

coding-grandpa.tistory.com

어찌해야할지 모르겠어서 위 코드를 참고했다...퓨

class Solution {
    public int solution(int[][] lines) {
        
        int[] arr = new int[200];
        int answer = 0;
        
        // lines 정보를 arr배열에 적용
        for(int i=0 ; i < lines.length ; i++) {
            for(int j = lines[i][0] + 100 ; j < lines[i][1] + 100 ; j++) {
                arr[j]++;
            }
        }
        
        // 겹친 부분 세기
        for(int i=0 ; i < 200 ; i++) {
            if(arr[i] > 1) {
                answer++;
            }
        }
        
        return answer;
    }
}

+100은 왜 해줬는지 모르겠어서 강의를 봤다.

 

 

lines[][]에 들어오는 값들에 음수가 들어올 수 있는데

들어오는 값에 100씩 더해 양수만 가질 수 있게 한 것이고,

이렇게 치환한 거..라고 한다. (-100~100은 0~200과 동일하니까 )

 

우와 강의 굿...ㅠ

반응형