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

youngkyu MIn·2023년 10월 9일

문제링크 - 프로그래머스 - 겹치는 선분의 길이

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Solution {
    public int solution(int[][] lines) {
        List<int[]> points = new ArrayList<>();

        for(int[] line : lines) {
            points.add(new int[]{line[0], 1});
            points.add(new int[]{line[1], -1});
        }

        Collections.sort(points, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));

        int count = 0;
        int prevX = points.get(0)[0];
        int answer = 0;

        for(int[] point : points) {
            if(count >= 2) {
                answer += point[0] - prevX;
            }
            count += point[1];
            prevX = point[0];
        }

        return answer;
    }
}
profile
한 줄 소개

0개의 댓글