[LeetCode] Points That Intersect With Cars

아르당·2026년 11월 12일

LeetCode

목록 보기
591/604
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

인덱스가 0부터 시작하는 2차원 정수 배열 nums가 주어지고, 숫자 라인에 주차된 자동차의 좌표를 나타낸다. 각 인덱스 i에 대해, nums[i] = [starti, endi]이고, starti는 i번째 자동차의 시작 지점, endi는 자동차의 끝 지점이다.
라인에서 자동차의 일부가 덮여 있는 정수 좌표의 개수를 반환해라.

Example

#1
Input: nums = [[3, 6], [1, 5], [4, 7]]
Output: 7
Explanation: 1부터 7까지 모든 점이 최소 한 대의 자동차과 교차해서, 답은 7이다.

#2
Input: nums = [[1, 3], [5, 8]]
Output: 7
Explanation: 최소 한 대의 자동차 교차하는 점는 1, 2, 3, 5, 6, 7, 8이다. 총 7개의 점이 있고, 답은 7이다.

Constraints

  • 1 <= nums.length <= 100
  • nums[i].length == 2
  • 1 <= starti <= end <= 100

Solved

class Solution {
    public int numberOfPoints(List<List<Integer>> nums) {
        int[] line = new int[102];

        for(List<Integer> num : nums){
            line[num.get(0)]++;
            line[num.get(1) + 1]--;
        }

        int ans = 0;
        int count = 0;

        for(int i = 0; i < 102; i++){
            count += line[i];
            if(count > 0){
                ans++;
            }
        }
        
        return ans;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글